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 小时前
算法题解记录--239滑动窗口最大值
数据结构·算法
额,不知道写啥。9 小时前
HAO的线段树(中(上))
数据结构·c++·算法
blackicexs10 小时前
第五周第七天
数据结构·算法
夏乌_Wx11 小时前
反转链表:三种实现思路与细节梳理
数据结构·链表
紫陌涵光12 小时前
108.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
载数而行52013 小时前
算法系列2之最短路径
c语言·数据结构·c++·算法·贪心算法
fu的博客13 小时前
【数据结构10】满/完全二叉树、顺序/链式存储
数据结构·
逆境不可逃13 小时前
【除夕篇】LeetCode 热题 100 之 189.轮转数组
java·数据结构·算法·链表
wefg114 小时前
【算法】倍增思想(快速幂)
数据结构·c++·算法
Zik----14 小时前
Leetcode24 —— 两两交换链表中的节点(迭代法)
数据结构·算法·链表