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

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

相关推荐
2401_834636991 小时前
Linux 负载均衡全实战:Nginx+HAProxy+LVS 从原理到落地
linux·nginx·负载均衡
鹏大师运维7 小时前
为什么信创电脑装软件总提示“软件包架构不匹配”?
linux·运维·架构·国产化·麒麟·deb·统信uos
小欣加油7 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
鹤落晴春9 小时前
【Linux复习】管理SELinux安全性
linux·运维·服务器
yz_aiks9 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
bjzhang7510 小时前
CentOS下安装MySQL详解
linux·mysql·centos
8Qi811 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
Jason_chen12 小时前
Linux 6.2 音频机制深度解析:AI驱动的低延迟音频与零信任音频安全架构
linux
下午写HelloWorld12 小时前
Linux系统及Ubuntu常用指令
linux·ubuntu·操作系统
weixin_5231853213 小时前
Collections.unmodifiableMap详解:真的不可修改吗?
java·linux·前端