博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Lists
阅读量:5893 次
发布时间:2019-06-19

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

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

 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.

转载于:https://www.cnblogs.com/jcliBlogger/p/4624418.html

你可能感兴趣的文章
-Java- Maven命令
查看>>
struts2文件下载
查看>>
Jackson 框架,轻易转换JSON
查看>>
u-boot传递cmdline 开启kernel打印
查看>>
注解学习day_1
查看>>
java内存堆栈与引用之间的关联
查看>>
ubuntu中安装sqldeveloper和JDK 1.7
查看>>
jsp如何实现下载文件的功能
查看>>
Java之LinkedList源码解读(JDK 1.8)
查看>>
html禁止清除input文本输入缓存
查看>>
安装ubuntu/win7后选择win7出现 a read disk error occurred
查看>>
WebStorm主题设置
查看>>
RDS
查看>>
HibernateTemplate 和HibernateDaoSupport的session
查看>>
Linux下内网反弹技巧总结与杂谈
查看>>
Mysql(Mariadb)数据库主从复制
查看>>
MapReduce:详解Shuffle过程
查看>>
选择排序
查看>>
【C语言学习】国嵌22__数组基础
查看>>
JVM三个时代
查看>>