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

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

相关推荐
孙克旭_几秒前
day051-ansible循环、判断与jinja2模板
linux·运维·服务器·网络·ansible
渡我白衣26 分钟前
Linux操作系统之进程间通信:共享内存
linux
Mr_Orangechen1 小时前
Linux 下使用 VS Code 远程 GDB 调试 ARM 程序
linux·运维·arm开发
??tobenewyorker2 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔2 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
lilian1292 小时前
linux系统mysql性能优化
linux·运维·mysql
共享家95272 小时前
linux_线程概念
linux·开发语言·jvm
乌云暮年3 小时前
Linux常用命令
linux·服务器·ssh·php
weixin_516023073 小时前
Geant4 安装---Ubuntu
linux·运维·ubuntu
稀液蟹-plus3 小时前
zynq-PS篇——bperez77中DMA驱动注意事项
linux·fpga