LeetCode:206.反转链表

方法一 递归

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

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

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