码迷,mamicode.com
首页 > 其他好文 > 详细

206.Reverse Linked List

时间:2018-05-11 12:57:31      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:one   targe   href   技术   reverse   linked   close   要求   isp   

题目链接

题目大意:翻转单链表。要求用递归和非递归两种方法。

法一:非递归。直接对原单链表进行循环操作,且不新开辟空间,用头插法即可。代码如下(耗时0ms):

技术分享图片
 1     public ListNode reverseList(ListNode head) {
 2         if(head == null) {
 3             return head;
 4         }
 5         ListNode res = head;
 6         head = head.next;
 7         res.next = null;
 8         while(head != null) {
 9             ListNode tmp = head;
10             //head=head.next一定要放在tmp.next=res的前面
11             //因为如果放在后面,tmp.next=res就会改变head.next的值,这样head就不能正常指向原值,会造成死循环
12             head = head.next;
13             //下面是头插法
14             tmp.next = res;
15             res = tmp;
16         }
17         return res;
18     }
View Code

法二:递归。还不是很明白。代码如下(耗时1ms):

技术分享图片
 1     public ListNode reverseList(ListNode head) {
 2         if(head == null || head.next == null) {
 3             return head;
 4         }
 5         //头节点没有记录,因为头节点会成为尾结点
 6         ListNode nextHead = head.next;
 7         //res保证每次return的都是头结点
 8         ListNode res = reverseList(head.next);
 9         //return之后,开始组装结点,其实这里是尾插的思想
10         //依次会是5->4,4->3,3->2,2->1
11         nextHead.next = head;
12         //下面的这个操作不知是为啥。。。
13         head.next = null;
14         return res;
15     }
View Code

 

206.Reverse Linked List

标签:one   targe   href   技术   reverse   linked   close   要求   isp   

原文地址:https://www.cnblogs.com/cing/p/9023556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!