Sunday, April 5, 2015

143. Reorder List Leetcode Java

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
Solution:
3 steps:
1.Cut the list to two halves.
2.Reverse the second half of the list
3.Insert the second half nodes to first half of the list
Time complexity: O(n) in place
 public void reorderList(ListNode head) {  
     if(head==null || head.next==null) return;  
     ListNode walker=head;  
     ListNode runner=head;  
     while(runner!=null && runner.next!=null){  
       walker=walker.next;  
       runner=runner.next.next;  
     }  
     ListNode tail=walker.next;  
     if(tail==null) return;   
     while(tail.next!=null){  
       ListNode cur=tail.next;  
       tail.next=cur.next;  
       cur.next=walker.next;  
       walker.next=cur;  
     }  
     ListNode pre=head;  
     while(walker.next!=null){  
       ListNode cur=walker.next;  
       walker.next=cur.next;  
       cur.next=pre.next;  
       pre.next=cur;  
       pre=cur.next;  
     }  
   }  

No comments:

Post a Comment