1. 程式人生 > 其它 >連結串列-206. 反轉連結串列

連結串列-206. 反轉連結串列

https://leetcode-cn.com/problems/reverse-linked-list/

1.題目描述

給你單鏈表的頭節點 head ,請你反轉連結串列,並返回反轉後的連結串列

2.思路

用二個指標,pre指向反轉連結串列的首結點,curr指向連結串列的首結點,每次將curr->next指向pre
可以迭代,可以遞迴

3.1迭代法:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr;
        ListNode *curr = head;
        while(curr)
        {
           ListNode *p = curr;
           curr = curr->next;
           p->next = pre;
           pre = p;
        }
        return pre;
    }
};

3.2遞迴法

遞迴是逆序完成逆轉,遞迴返回

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    if(!head || !head->next) return head;

    ListNode *p = reverseList(head->next); //p always points to the last node of the linklist, which is also the first node of the reverseList
    head->next->next = head;
    head->next = nullptr; // the last node->next of the reverseList must point to null

    return p;

    }
};