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;
    }
};

 当然有时候会需要不只是箭头方向的改变,而是节点位置的真实变动,如判断链表是否是回文的第三种做法。此时就需要如下这么做:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode* cur = head;
        ListNode* NewH = new ListNode(-1);
        NewH ->next = head;
        while(cur->next){
            ListNode* tmp = cur->next;
            cur->next = tmp->next;
            tmp->next = NewH->next;
            NewH->next = tmp;
        }
        ListNode* Head = NewH -> next;
        delete NewH;
        return Head;
    }
};

 

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

 

你可能感兴趣的:(LeetCode)