首页 > 其他 > 详细

LeetCode:206.反转链表

时间:2020-04-11 15:48:57      阅读:66      评论:0      收藏:0      [点我收藏+]

 

方法一 递归

前后指正的转换,需要一个临时指针来存后一个节点,最后实现当前指针的后移。

/**
 * 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;
        while(cur != NULL){
            ListNode* tmp = cur -> next; //tmp = old cur -> next
            cur -> next = pre; //old pre
            pre = cur; //new pre = old pre
            cur = tmp; // new cur = tmp(old cur -> next)

        }
       return pre;
    }
};

 

方法二 递归
假设链表为1->2->3->4->5,层层递归
1、当递归到最后reverseList(5)(head=head->next=4->next=5)时,head->next=NULL返回head(即5,p指向5),这层递归结束。
2、reverseList(5)(head->next=4->next=5)后的代码是head->next->next = head(5->next=4即5->4);head->next = NULL(4->NULL);return p(返回5->4->NULL);
3、再看reverseList(4)(head->next=3->next=4)后中后head->next->next = head(4->3);head->next = NULL(3->NULL);return p(返回5->4->3->NULL);
4、reverseList(2), reverseList(1)依次类推,p最终为5->4->3->2->1->NULL。

作者:24shi-01fen-_00_01
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/206fan-zhuan-lie-biao-die-dai-di-gui-by-24shi-01fe/

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode* p = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return p;
    }
};

 

LeetCode:206.反转链表

原文:https://www.cnblogs.com/BillowJ/p/12679541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!