【leetcode】反转链表

大家好,我是苏貝,本篇博客带大家刷题,如果你觉得我写的还不错的话,可以给我一个赞👍吗,感谢❤️


目录

  • [方法1 .将箭头方向逆转](#方法1 .将箭头方向逆转)
  • 方法2.

点击查看题目

方法1 .将箭头方向逆转

思路:

n1,n2,n3分别指向NULL,head,head->next

用循环,每次都让n2->next指向n1,再让n1=n2,n2=n3,n3=n3->next

c 复制代码
struct ListNode* reverseList(struct ListNode* head) {
    if(head==NULL)
        return NULL;
    struct ListNode* n1=NULL;
    struct ListNode* n2=head;
    struct ListNode* n3=head->next;
    while(n2)
    {
        n2->next=n1;

        n1=n2;
        n2=n3;
        if(n3)
            n3=n3->next;        
    }
    return n1;
}

方法2.

思路

3个变量,cur=head,tail=NULL,next=cur->next

用循环,每次都让cur->next指向tail,再让tail=cur,cur=next

c 复制代码
struct ListNode* reverseList(struct ListNode* head) {

    struct ListNode* cur=head;
    struct ListNode* tail=NULL;
    while(cur)
    {
        struct ListNode* next=cur->next;
        cur->next=tail;
        tail=cur;
        cur=next;
    }
    return tail;
}

好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️

相关推荐
南棱笑笑生1 分钟前
20251106给荣品RD-RK3588-MID开发板跑Rockchip的原厂Android13系统时禁止锁屏+永不休眠
linux·运维·服务器·rockchip
赖small强12 分钟前
Linux 优先级反转问题详解与处理方案
linux·优先级反转·优先级继承·缩短临界区
小当家.10520 分钟前
[LeetCode]Hot100系列.贪心总结+思想总结
算法·leetcode·职场和发展
wdfk_prog44 分钟前
[Linux]学习笔记系列 -- [kernel][time]timekeeping
linux·笔记·学习
yuanManGan1 小时前
走进Linux的世界:冯诺依曼体系结构
linux
小白银子1 小时前
零基础从头教学Linux(Day 60)
linux·数据库·mysql·oracle
new_daimond1 小时前
Linux 服务器内存监控与优化指南
linux·服务器·chrome
im_AMBER1 小时前
Leetcode 46
c语言·c++·笔记·学习·算法·leetcode
一介草民丶2 小时前
Linux | Mongodb 6 离线安装
linux·运维·mongodb
赖small强2 小时前
Linux 线程相关结构对照表与关系图
linux·thread_info·task_struct·thread_struct