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;
}
相关推荐
暮色_年华1 天前
随想 2:对比 linux内核侵入式链表和 STL 非侵入链表
linux·c++·链表
晚风吹长发1 天前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法
SWAGGY..1 天前
数据结构学习篇(10)--- 二叉树基础oj练习
数据结构·学习
千谦阙听1 天前
双链表:比单链表更高效的增删查改
数据结构·链表·visual studio
xie_pin_an1 天前
从二叉搜索树到哈希表:四种常用数据结构的原理与实现
java·数据结构
栈与堆1 天前
LeetCode 21 - 合并两个有序链表
java·数据结构·python·算法·leetcode·链表·rust
viqjeee1 天前
ALSA驱动开发流程
数据结构·驱动开发·b树
XH华1 天前
数据结构第九章:树的学习(上)
数据结构·学习
我是大咖1 天前
二维数组与数组指针
java·数据结构·算法
爱编码的傅同学1 天前
【今日算法】Leetcode 581.最短无序连续子数组 和 42.接雨水
数据结构·算法·leetcode