LC_206. Reverse Linked List

 

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
      if (head == null || head.next == null) return head ;
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 的尾巴,也就是新头。

 

posted @ 2018-02-21 11:11  davidnyc  阅读(111)  评论(0编辑  收藏  举报