链表 | LeetCode 206 反转链表

73 阅读1分钟

题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

本题思路

就是将原本链表的指向转变为向前指。本来是前一个元素指向后一个,现在一个个节点改为后一个指向前一个

双指针法

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* cur = head; //cur来遍历整个链表
        while (cur) { 
            ListNode* tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

因为反转链表需要断开首个元素和第二元素之间的指向,所以要先保存第二元素的地址tmp。接着将首个元素(cur指向首个元素)的next指向新建的空指针(pre指向空指针)。pre指向首个元素,cur指向第二元素以此类推。

递归法

class Solution {
public:
    ListNode* reverse(ListNode* cur, ListNode* pre) {
        if (cur == nullptr)
            return pre;
        ListNode* tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
        return reverse(cur, pre);
        // return reverse(tmp, cur);
    }
    ListNode* reverseList(ListNode* head) { return reverse(head, nullptr); }
};
class Solution {
public:
    ListNode* reverse(ListNode* cur, ListNode* pre) {
        if (cur == nullptr)
            return pre;
        ListNode* tmp = cur->next;
        cur->next = pre;
        // pre = cur;
        // cur = temp;
        // return reverse(cur, pre);
        return reverse(tmp, cur);//将其上面注释的操作进行简化
    }
    ListNode* reverseList(ListNode* head) { return reverse(head, nullptr); }
};

递归两个代码都可以后者更为精简