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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 203. Remove Linked List Elements【链表】简单
下一篇:LeetCode C++ 100. Same Tree【Tree/DFS/BFS】简单

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月15日 01时37分36秒