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 小时前
力扣热题100-------169.多数元素
java·数据结构·算法·leetcode·多数元素
艾莉丝努力练剑2 小时前
【数据结构与算法】顺序表和链表、栈和队列、二叉树、排序等数据结构的完整代码收录
c语言·数据结构·学习·链表
啊阿狸不会拉杆2 小时前
《算法导论》第 3 章 - 函数的增长
开发语言·数据结构·c++·算法
柠檬味的薄荷心3 小时前
【数据结构】双链表
数据结构
Aczone283 小时前
数据结构(三)双向链表
java·数据结构·链表
无敌的大魔王3 小时前
数据结构 实现单链表
数据结构
MSXmiao5 小时前
2048小游戏
数据结构·c++·算法
钮钴禄·爱因斯晨5 小时前
数据结构 | 树的秘密
c语言·开发语言·数据结构
2301_763994717 小时前
c++11特性
数据结构·c++·算法
快去睡觉~7 小时前
力扣148:排序链表
算法·leetcode·链表