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

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

相关推荐
q***133419 分钟前
Linux系统离线部署MySQL详细教程(带每步骤图文教程)
linux·mysql·adb
小雪_Snow1 小时前
Ubuntu 安装教程
linux·ubuntu
IT逆夜1 小时前
linux系统安全及应用
linux·运维
flashlight_hi2 小时前
LeetCode 分类刷题:404. 左叶子之和
javascript·算法·leetcode
Forest_HAHA2 小时前
<10>_Linux网络基础(上)
linux·服务器
小白程序员成长日记3 小时前
2025.11.19 力扣每日一题
算法·leetcode·职场和发展
c++逐梦人3 小时前
Linux下的编辑器vim的介绍
linux·编辑器·vim
大锦终4 小时前
【Linux】Reactor
linux·运维·服务器·c++
爱吃面条的猿4 小时前
Python修改pip install 指定安装包的路径和默认镜像源
linux·python·pip
代码AC不AC4 小时前
【Linux】版本控制器Git
linux·git·gitee