LeetCode206. Reverse Linked List(反转链表)

题目连接:https://leetcode.com/problems/reverse-linked-list/spa

方法一:迭代反转.net

https://blog.csdn.net/qq_17550379/article/details/80647926讲的很清楚code

/**
 * 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) {
        ListNode* pre = NULL;
        ListNode* cur = head;
        ListNode* lat;
        while(cur){
            lat = cur -> next;
            cur -> next = pre;
            pre = cur;
            cur = lat;
        }
        return pre;
    }
};

方法二:递归反转blog

解决递归问题从最简单的case入手。递归

(1)例如,对于链表1->2->3->4->5,leetcode

reverseList(head)返回的是5->4->3->2->1;get

reverseList(head->next)返回的是5->4->3->2;(由于head->next所指代的链表是2->3->4->5->NULL)it

以此类推。io

(2)对于reverseList(3)这个状况,此时head为3,head->next为4,此时链表状况以下:class

1->2->3->4<-5

 head->next->next=head这一操做后,链表变为:

 而后,head->next=NULL,即

1->2->3<-4<-5 

 

/**
 * 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 == NULL || head -> next == NULL)
            return head;
        ListNode *ans = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return ans;
    }
};

此外,提供一个错误写法:

/**
 * 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 == NULL || head -> next == NULL)
            return head;
        ListNode *ans = reverseList(head -> next);
        ans -> next = new ListNode(head -> val);
        return ans;
    }
};

 这种写法的错误之处在于:

以reverseList(3)为例,虽然ListNode *ans = reverseList(head -> next);返回的是5->4这个链表,不过ans指的是这个链表的第一个结点5,而后ans->next=new ListNode(head->val)后,其实在当前这一层递归中最终return的是5->3这个链表,并非返回想象中的5->4->3这个链表。

 

参考:https://blog.csdn.net/qq_17550379/article/details/80647926

相关文章
相关标签/搜索