博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
逆置单链表
阅读量:7057 次
发布时间:2019-06-28

本文共 1252 字,大约阅读时间需要 4 分钟。

我自己的方法是用的递归,毕竟也是接触了一点点点点点点 scheme 的骚年是吧,代码如下:

ListNode* reverseList(ListNode* head) {    if (head == nullptr){        return nullptr;    }        ListNode* newHead = nullptr;        function
reverse; reverse = [&](ListNode* node) { if (node->next == nullptr){ newHead = node; return; } reverse(node->next); node->next->next = node; node->next = nullptr; }; reverse(head); return newHead;}

毕竟是递归,我琢磨着会不会迭代会快一点,于是有了如下版本:

ListNode* reverseList(ListNode* head) {    if (head == nullptr || head->next == nullptr){        return head;    }        ListNode* previous = head;    ListNode* current  = head->next;    ListNode* next     = nullptr;    while (current != nullptr){        next = current->next;        current->next = previous;        previous = current;        current  = next;    }    head->next = nullptr;    return previous;}

 结果也是 8ms 啊,令人失望。

然后这是在过了一周之后,我写的代码:

ListNode* reverseList(ListNode* head){    if (head == nullptr || head->next == nullptr){        return head;    }        auto newHead = reverseList(head->next);    head->next->next = head;    head->next = nullptr;    return newHead;}

 

转载于:https://www.cnblogs.com/wuOverflow/p/4702567.html

你可能感兴趣的文章
Dropbox Folder Sync – 让 Dropbox 同步任意文件夹
查看>>
PHP 网页爬虫
查看>>
用户队列服务API
查看>>
C# word开发
查看>>
spring mvc 与 jasper Report集成
查看>>
java学习笔记14--动态代理
查看>>
最简单的可取消多选效果(以从水果篮中挑选水果为例)【jsDEMO】
查看>>
worksteal thread pool
查看>>
视频数据采集模块设计
查看>>
跟我extjs5(38--单个模块的设计[6获得模块列表数据])
查看>>
centos MySQL主从配置 ntsysv chkconfig setup命令 配置MySQL 主从 子shell MySQL备份 kill命令 pid文件 discuz!论坛数...
查看>>
Oracle修改默认字符编码
查看>>
HDU ACM 2845 Beans->动态规划
查看>>
EBS创建相应的用户
查看>>
android国际化(多语言)
查看>>
贝勒爷教你怎样在Mac上安装Microsoft Office
查看>>
SQL Server,MySQL,Oracle三者的区别
查看>>
ssh -v root@xxxxx 显示登录的细节
查看>>
负载均衡的场景下ASP.NET Core如何获取客户端IP地址
查看>>
crtmpserver系列之一:流媒体概述
查看>>