leetcode——206. 反转链表

头依次拔下来,按顺序插进另一个链表:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        new_head=None
        while head:
            tmp=head.next
            head.next=new_head
            new_head=head
            head=tmp
        return new_head
执行用时 :44 ms, 在所有 python3 提交中击败了93.17%的用户
内存消耗 :14.9 MB, 在所有 python3 提交中击败了19.62%的用户
 
 
 
 
——2019.10.24
 
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dump = new ListNode(-1);
        ListNode p = dump.next;
        ListNode q;
        while(head != null){
            q = new ListNode(head.val);
            dump.next = q;
            q.next = p;
            p = q;
            head = head.next;
        }
        return dump.next;
    }
}

 

 

 
posted @ 2019-10-24 20:47  欣姐姐  阅读(94)  评论(0编辑  收藏  举报