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;
}
相关推荐
666HZ6669 小时前
数据结构4.0 串
c语言·数据结构·算法
你撅嘴真丑11 小时前
蛇形填充数组 与 查找最接近的元素
数据结构·c++·算法
blackicexs11 小时前
第四周第四天
数据结构·c++·算法
Pluchon11 小时前
硅基计划4.0 算法 简单实现B树
java·数据结构·b树·算法·链表
im_AMBER11 小时前
Leetcode 119 二叉树展开为链表 | 路径总和
数据结构·学习·算法·leetcode·二叉树
DN202012 小时前
当AI开始评估客户的“成交指数”
数据结构·人工智能·python·microsoft·链表
Vic1010113 小时前
算法D1-20260212:双指针专题
java·数据结构·算法
9359613 小时前
机考24 翻译18 单词11
c语言·数据结构·算法
无聊的小坏坏14 小时前
一文讲通:二分查找的边界处理
数据结构·c++·算法