LeetCode206反转链表

思路:关键在于,不要引起链表混乱,以及不要丢失链表,所以要注意指针的先后顺序

错误代码

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head)
{
    //
    struct ListNode *pre=head;
    struct ListNode *cur=head;
    while(cur!=NULL)
    {
        cur=pre->next;//在这里会出现指针混淆,cur先更新为pre->next,后cur->next又指回pre,此时要把pre往后跳就会出现错误,因为逻辑上我们是希望pre跳到cur,但是cur的下一个指向了pre,所以就出现了逻辑bug
        cur->next=pre;
        pre=pre->next;
    }
    head->next=NULL;
    head=cur;
    return head;
}

AC代码

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head)
{
    //
    struct ListNode *pre=NULL;
    struct ListNode *cur=head;
    while(head!=NULL)
    {
        //必须先让cur记住head->next,如果先让head->next指向null,那么head后续节点会丢失
       cur=head->next;
       //链表转向
       head->next=pre;
       //pre是后指针,跟上
       pre=head;
       //head指针往前跳
       head=cur;

    }
    //循环终止是head=null,那么pre是后指针,终止的时候刚好指向最后一个节点,所以返回pre
    return pre;
}
相关推荐
小七在进步6 小时前
数据结构:栈与队列之栈的实现
数据结构
小小龙学IT7 小时前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
变量未定义~8 小时前
单调栈、单调队列(模板)、子矩阵(模板)
数据结构·算法·蓝桥杯
不会就选b8 小时前
算法日常・每日刷题--<快速排序>2
数据结构·算法
kyle~9 小时前
Schema---数据结构的形式化规则描述
数据结构·windows·microsoft
李小小钦10 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
先吃饱再说11 小时前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
gugucoding1 天前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL1 天前
我的数据结构3——链表(link list)
数据结构·链表
王老师青少年编程1 天前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月