日野弥生:勉強しよう

LeetCode 206 - 反转链表

发表于2025年01月17日

#链表 #递归

在遍历链表时,将当前节点的 next 指针改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

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

通过此题能看出,Leecode并没有把头节点当成一个特殊节点仅用来表示头,而是,头节点本身也是一个普通的带数值的节点。

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/reverse-linked-list/

上一篇

LeetCode 160 - 相交链表

下一篇

LeetCode 19 - 删除链表的倒数第N个节点