【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;
}

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

相关推荐
WuYiCheng66621 分钟前
CentOS高手之路:从进阶实战到企业级优化
linux·运维·centos
猴子请来的逗比48922 分钟前
mysql的安装方式
linux·数据库·学习·mysql
非自律懒癌患者1 小时前
ubuntu 20.04 ping baidu.coom可以通,ping www.baidu.com不通 【DNS出现问题】解决方案
linux·tcp/ip·ubuntu
Xam_d_LM1 小时前
【Linux】如何清除 Ubuntu 留下的 EFI 分区,Windows 磁盘管理器右键删除卷是灰色
linux·运维·windows·ubuntu·重装系统·磁盘管理器
freyazzr1 小时前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
黄暄1 小时前
Linux项目部署全攻略:从环境搭建到前后端部署实战
java·linux·运维·服务器·前端·后端·持续部署
freyazzr2 小时前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论
珊瑚里的鱼2 小时前
【滑动窗口】LeetCode 1004题解 | 最大连续1的个数 Ⅲ
开发语言·c++·笔记·算法·leetcode
独行soc2 小时前
2025年渗透测试面试题总结-安恒[实习]安全服务工程师(题目+回答)
linux·数据库·安全·web安全·面试·职场和发展·渗透测试
L汐2 小时前
01 CentOS根分区满了扩容
linux·运维·centos