1. 程式人生 > >Leetcode206 反轉連結串列(C++和python實現)

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