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;
}
相关推荐
Genevieve_xiao5 小时前
【数据结构】【xjtuse】八股文单元小测
数据结构·算法
想唱rap7 小时前
Linux下进程的状态和优先级
linux·运维·服务器·开发语言·数据结构·算法
Croa-vo8 小时前
逆袭Akuna Quant!美硕秋招亲历,从网申到拿offer全攻略
数据结构·经验分享·算法·面试·职场和发展
vir029 小时前
交换瓶子(贪心)
数据结构·算法
墨染点香10 小时前
LeetCode 刷题【160. 相交链表】
算法·leetcode·链表
YoungHong199210 小时前
面试经典150题[066]:分隔链表(LeetCode 86)
leetcode·链表·面试
9523610 小时前
数据结构-二叉树
java·数据结构·学习
HUTAC11 小时前
重要排序算法(更新ing)
数据结构·算法
冉佳驹11 小时前
数据结构 ——— 八大排序算法的思想及其实现
c语言·数据结构·排序算法·归并排序·希尔排序·快速排序·计数排序
Hello_Embed12 小时前
FreeRTOS 入门(四):堆的核心原理
数据结构·笔记·学习·链表·freertos·