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 分钟前
河南萌新联赛2026第(四)场:南阳理工学院
数据结构·c++·算法·贪心算法·stl·动态规划
Nil2087 小时前
leetcode 138随机链表的复制
算法·leetcode·链表
疯狂打码的少年8 小时前
【数据结构】图的遍历:深度优先搜索(DFS)
数据结构·笔记·算法·深度优先
Nil20810 小时前
leetcode 24两两交换链表中的节点
算法·leetcode·链表
土司大王12 小时前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
神威难绷泪15 小时前
数据结构:哈希表 算法相关 排序算法
数据结构
Zguigo17 小时前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
2401_8697695918 小时前
list 2
数据结构·list
ambition2024221 小时前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
疯狂打码的少年1 天前
【数据结构】图的存储结构:邻接矩阵与邻接表
数据结构·笔记