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

LC_206. Reverse Linked List

时间:2018-02-21 12:23:29      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:==   lis   wan   point   post   opp   ems   null   ase   

 

https://leetcode.com/problems/reverse-linked-list/description/
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
test case: 3->1->2>5 to 5->2->1->3
x c
 1 public class LC206_ReverseLinkedList {
 2     public ListNode reverseLinkedList(ListNode head){
 3         if (head == null || head.next == null) return head ;
 4         ListNode prev = null, curr= head, next = null ;
 5         /*
 6         * 细节, 如果 写成curr.next != null, curr 会在 NODE4 但是没有进入循环,所以并不会连上前面的点,
 7         * 所以返回的时候会是一个单点,而不是链表
 8         * thats the reason curr should be stopped at null to make sure all prev nodes linked.
 9         * */
10         while (curr != null ){
11             next = curr.next ;
12             curr.next = prev ;
13             prev = curr ;
14             curr = next ;
15         }
16         return prev ;
17     }
18 
19     public ListNode reverseLinkedList2(ListNode head){
20         //base
21         /*
22         * 1-2-3-4   null<-1<-2<-3<-4
23         * current iteration head =2  expect null<-3<-4
24         *
25         * */
26         ListNode newHead = reverseLinkedList2(head.next) ;
27         ListNode tail = head.next ; //3
28         tail.next  = head ; //2<-3<-4
29         head.next = null;  //null<-2<-3<-4
30         return newHead ;
31     }
32 }

 

 

 

recursive:   assume Node2 is the head,  subproblem return:

                null<-Node3 <- Node4  

then you want to change to

技术分享图片

 

ListNode newHead = reverse(head.next) will generate the following pic: 

ListNode tail = head.next ;  here tail is Node 3

note here since we didnt touch head, thats the reason node2 still points to node3

技术分享图片

 

tail.next = head

 技术分享图片

 

head.next = null;   //this is what you need to return for the upper level recursive

技术分享图片

 

因为这里是recursive, 一层层走下去 reverse(head.next) 所以base case:

if(head == null || head.next == null) 最后head 会是 原 linkedlist 的尾巴,也就是新头。

 

LC_206. Reverse Linked List

标签:==   lis   wan   point   post   opp   ems   null   ase   

原文地址:https://www.cnblogs.com/davidnyc/p/8456363.html

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