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;
}
相关推荐
GG不是gg6 小时前
B树与B+树全面解析
数据结构·b树·b+树
鸡鸭扣9 小时前
leetcode hot100:解题思路大全
数据结构·python·算法·leetcode·力扣
ooppoop45610 小时前
嵌入式学习笔记 D21:双向链表的基本操作
笔记·学习·链表
被AI抢饭碗的人10 小时前
算法题(150):拼数
数据结构·算法
一梦浮华10 小时前
自学嵌入式 day19-数据结构 链表
数据结构·链表
梁辰兴12 小时前
数据结构实验10.1:内部排序的基本运算
数据结构·c++·算法·排序算法·c·内部排序
charlie11451419112 小时前
Linux内核深入学习(4)——内核常见的数据结构2——红黑树
linux·数据结构·学习·红黑树
gyeolhada15 小时前
2025蓝桥杯JAVA编程题练习Day8
java·数据结构·算法·蓝桥杯
m0_7382065415 小时前
嵌入式学习的第二十三天-数据结构-树+哈希表+内核链表
数据结构·学习
freyazzr15 小时前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论