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

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

相关推荐
许小燚15 分钟前
线性表——双向链表
数据结构·链表
牧以南歌〆37 分钟前
在Ubuntu主机中修改ARM Linux开发板的根文件系统
linux·arm开发·驱动开发·ubuntu
夜月yeyue2 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
kfepiza2 小时前
Debian的`/etc/network/interfaces`的`allow-hotplug`和`auto`对比讲解 笔记250704
linux·服务器·网络·笔记·debian
晚云与城3 小时前
【数据结构】顺序表和链表
数据结构·链表
cuijiecheng20183 小时前
Ubuntu下布署mediasoup-demo
linux·运维·ubuntu
FirstFrost --sy4 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
独行soc5 小时前
2025年渗透测试面试题总结-2025年HW(护网面试) 33(题目+回答)
linux·科技·安全·网络安全·面试·职场和发展·护网
java龙王*5 小时前
开放端口,开通数据库连接权限,无法连接远程数据库 解决方案
linux
liulilittle6 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表