Leetcode206 反转链表(C++和python实现)

面试经常会考的题,先来看C++:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* cur = head;
        ListNode* NewH = NULL;
        while(cur!=NULL){
            ListNode* tmp = cur->next;
            cur->next = NewH;
            NewH = cur;
            cur = tmp;
        }
        return NewH;
    }
};

python可以同时赋值,所以不需要临时指针:

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur,prev = head,None
        while cur:
            cur.next,prev,cur = prev,cur,cur.next
        return prev

猜你喜欢

转载自blog.csdn.net/zpznba/article/details/83902389