1. 程式人生 > >LC_206. Reverse Linked List

LC_206. Reverse Linked List

pan top should post problems per div spa leetcode

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