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;
}
相关推荐
im_AMBER4 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢4 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
AI柠檬4 小时前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
zz0723207 小时前
数据结构 —— 栈
数据结构
Madison-No77 小时前
【C++】关于list的使用&&底层实现
数据结构·c++·stl·list·模拟实现
Bug退退退1237 小时前
ArrayList 与 LinkedList 的区别
java·数据结构·算法
2301_807997389 小时前
代码随想录-day26
数据结构·c++·算法·leetcode
TL滕9 小时前
从0开始学算法——第一天(认识算法)
数据结构·笔记·学习·算法
代码雕刻家13 小时前
1.4.课设实验-数据结构-单链表-文教文化用品品牌2.0
c语言·数据结构
云边有个稻草人13 小时前
Rust 借用分割技巧:安全解构复杂数据结构
数据结构·安全·rust