[LeetCode] Reverse Lists

Well, since the head pointer may also be modified, we create a new_head that points to it to facilitate the reverse process.

For the example list 1 -> 2 -> 3 -> 4 -> 5 in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4 -> 5 (we init new_head -> val to be 0). Then we set a pointer pre to new_head and another cur to head. Then we keep inserting cur -> next after pre until cur becomes the last node. The code is follows.

复制代码
 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         ListNode* new_head = new ListNode(0);
 5         new_head -> next = head;
 6         ListNode* pre = new_head;
 7         ListNode* cur = head;
 8         while (cur && cur -> next) {
 9             ListNode* temp = pre -> next;
10             pre -> next = cur -> next;
11             cur -> next = cur -> next -> next;
12             pre -> next -> next = temp;
13         }
14         return new_head -> next;
15     }
16 };
复制代码

This link provides a more concise solution without using the new_head. The idea is to reverse one node at a time for the beginning of the list. The rewritten code is as follows.

复制代码
 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         ListNode* pre = NULL;
 5         while (head) {
 6             ListNode* next = head -> next;
 7             head -> next = pre;
 8             pre = head;
 9             head = next;
10         }
11         return pre;
12     }
13 };
复制代码

Well, both of the above solutions are iterative. The hint has also suggested us to use recursion. In fact, the above link has a nice recursive solution, whose rewritten code is as follows.

复制代码
 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         if (!head || !(head -> next)) return head;
 5         ListNode* node = reverseList(head -> next);
 6         head -> next -> next = head;
 7         head -> next = NULL;
 8         return node;
 9     }
10 };
复制代码

The basic idea of this recursive solution is to reverse all the following nodes after head. Then we need to set head to be the final node in the reversed list. We simply set its next node in the original list (head -> next) to point to it and sets its next to be NULL.

posted @   jianchao-li  阅读(168)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
点击右上角即可分享
微信分享提示