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;
}
相关推荐
wabs6665 小时前
关于图论【最短路径之Bellman_ford 算法(单源有限最短路)|卡码网96.城市间货物运输III的思考】
数据结构·算法·图论·卡码网·bellman_ford·单源有限最短路
imaol16 小时前
链表 -- 环链表
java·前端·链表
wuyk5556 小时前
2.队列:先进先出的线性数据结构
c语言·数据结构·stm32·单片机
imaol17 小时前
链表 -- 双向链表
java·前端·链表
lsylalalala7 小时前
常见的排序算法1
数据结构·算法·排序算法
imaol18 小时前
数据结构---队列
java·数据结构·算法
疯狂打码的少年8 小时前
【数据结构】串的模式匹配:KMP算法(重点)
数据结构·笔记·算法
一米阳光86619 小时前
软考(中级)软件设计师核心笔记(8)数据结构——线性结构、数组、矩阵
数据结构·笔记·职场发展·软考·软件设计师·中级职称
疯狂打码的少年10 小时前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
小龙报12 小时前
【优选算法】1.搜索插入位置 2.x的平方根
java·c语言·数据结构·c++·python·算法·蓝桥杯