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

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

相关推荐
vortex525 分钟前
Linux Shell 中的 dash 符号 “-”
linux·运维·服务器
月堂29 分钟前
Linux操作系统-性能优化
linux·运维·服务器
夕泠爱吃糖2 小时前
Linux 文件内容的查询与统计
android·linux·c#
love530love2 小时前
【笔记】NVIDIA AI Workbench 中安装 cuDNN 9.10.2
linux·人工智能·windows·笔记·python·深度学习
果子⌂2 小时前
PostgreSQL --数据库操作
linux·数据库·postgresql
倔强的石头1063 小时前
【Linux指南】文件系统基础操作与路径管理
linux·运维·服务器
小呆瓜历险记4 小时前
ubuntu 22.04搭建SOC开发环境
linux·运维·ubuntu
码农101号4 小时前
Linux中shell流程控制语句
linux·运维·服务器
ajassi20004 小时前
开源 java android app 开发(十二)封库.aar
android·java·linux·开源
暗夜潜行5 小时前
ubuntu + nginx 1.26 + php7.4 + mysql8.0 调优
linux·运维·ubuntu