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;
}
相关推荐
এ᭄画画的北北8 分钟前
力扣-234.回文链表
算法·leetcode·链表
wuqingshun3141592 小时前
蓝桥杯 11. 打印大X
数据结构·算法·职场和发展·蓝桥杯·深度优先
wuqingshun3141594 小时前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
长沙火山5 小时前
9.ArkUI List的介绍和使用
数据结构·windows·list
AAAA劝导tx6 小时前
List--链表
数据结构·c++·笔记·链表·list
格格Code6 小时前
八大排序——冒泡排序/归并排序
数据结构·算法·排序算法
fantasy_46 小时前
LeetCode238☞除自身以外数组的乘积
java·数据结构·python·算法·leetcode
Phoebe鑫7 小时前
数据结构每日一题day12(链表)★★★★★
数据结构·算法·链表
八股文领域大手子8 小时前
深入浅出限流算法(三):追求极致精确的滑动日志
开发语言·数据结构·算法·leetcode·mybatis·哈希算法
新时代苦力工8 小时前
处理对象集合,输出Map<String, Map<String, List<MyObject>>>格式数据,无序组合键处理方法
java·数据结构·list