206. 反转链表

题目

自己一开始的思路是对链表的每个节点的val进行更改,然后就没有然后了……
没写出来

然后看了卡哥的讲解

感触最深的点是卡哥是让结点间的指向发生改变(换句话说,改变了节点的next),然后顺着这个思路卡哥给出了两个方法:双指针法和递归法。

img

特别要给卡哥的视频讲解点个大大的赞,所有的小细节都讲清楚了。

当然这个题目用虚拟头节点 + 头插法也是可以做出来的。

看了卡哥讲解后自己写的代码:

双指针法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *cur = head, *pre = nullptr;
        while (cur)
        {
            ListNode *tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

递归法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    ListNode* reverse(ListNode *cur, ListNode *pre)
    {
        if (cur == nullptr)
            return pre;

        ListNode *tmp = cur->next;
        cur->next = pre;
        return reverse(tmp, cur);
    }


    ListNode* reverseList(ListNode* head) {
        return reverse(head, nullptr);
    }
};

特别要说明的是自己又踩了下坑,就是这段:

if (cur == nullptr)
    return pre;

刚开始又写成了

if (cur)
    return pre; 

于是报错……

写if语句的判断条件一定要小心!!!

虚拟头节点 + 头插法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *dummyHead = new ListNode(0);
        ListNode *cur = head;
        while (cur)
        {
            ListNode *tmp = cur->next;
            cur->next = dummyHead->next;
            dummyHead->next = cur;
            cur = tmp;
        }
        return dummyHead->next;
    }
};
posted @   hisun9  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示