LeetCode C++ 206. Reverse Linked List【链表】简单
发布日期:2021-07-01 02:50:00
浏览次数:2
分类:技术文章
本文共 1060 字,大约阅读时间需要 3 分钟。
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULLOutput: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?题意:递归或者迭代地翻转一个单链表。
思路1:迭代翻转单链表。
代码:
class Solution { public: ListNode *reverseList(ListNode *head) { if (head == nullptr || head->next == nullptr) return head; ListNode *newHead = nullptr, *cur = head; while (cur) { ListNode *next = cur->next; cur->next = newHead; newHead = cur; cur = next; } return newHead; }};
效率:
执行用时:12 ms, 在所有 C++ 提交中击败了72.16% 的用户内存消耗:8.3 MB, 在所有 C++ 提交中击败了97.67% 的用户
思路2:递归翻转单链表。
代码:
class Solution { public: ListNode *reverseList(ListNode *head) { if (head == nullptr || head->next == nullptr) return head; ListNode *newHead = reverseList(head->next); head->next->next = head; head->next = nullptr; return newHead; }};
效率:
执行用时:8 ms, 在所有 C++ 提交中击败了95.96% 的用户内存消耗:8.5 MB, 在所有 C++ 提交中击败了55.25% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108177690 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月15日 01时37分36秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
location区段
2019-04-30
linux内存的寻址方式
2019-04-30
how2heap-double free
2019-04-30
tf keras SimpleRNN源码解析
2019-04-30
MyBatisPlus简单入门(SpringBoot)
2019-04-30
xss-labs详解(上)1-10
2019-04-30
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-04详解
2019-04-30
Linux png转jpg (convert命令)
2019-04-30
vscode git
2019-04-30
CodeForces - 456C Boredom (dp)
2019-04-30
CodeForces - 1042B Vitamins (思维)
2019-04-30
ACM 2013 长沙区域赛 Collision (几何)
2019-04-30
ACM 2014 鞍山区域赛 E - Hatsune Miku (dp)
2019-04-30
反向传播&梯度下降 的直观理解程序(numpy)
2019-04-30
ACM 2017 北京区域赛 J-Pangu and Stones(区间dp)
2019-04-30
java常用类 String面试题
2019-04-30
四线触摸屏原理
2019-04-30
C/C++如何返回一个数组/指针
2019-04-30