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

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

相关推荐
程序员-Benothing14 小时前
Linux安全加固指南:账号、权限、服务、审计基线
linux·运维·安全
木子欢儿17 小时前
openconnect Linux客户端安装 以及开机自启和登录
linux·运维·服务器
..Dauntless..17 小时前
【Linux】文件系统(一)
linux·运维·服务器
GeW20 小时前
新质生产力路线图:从Linux到数据库,企业落地要点都在这
linux
java_nnnn20 小时前
LeetCode刷题滑动窗口(水果成篮+找到字符串中所有字母的异位词)Java
java·开发语言·leetcode
IMPYLH20 小时前
Linux 系统备份与镜像
linux·服务器·网络
qetfw20 小时前
Bash 字符串处理:参数展开、序列与脚本执行方式
linux·开发语言·chrome·bash
hhwyqwqhhwy20 小时前
设备树之 provider 和 consumer
java·linux·前端
aaa最北边21 小时前
Linux 上的交叉编译
linux·运维·服务器
小张成长计划..21 小时前
【Linux】27:日志
linux·运维·服务器