Saturday, October 14, 2017

328. Odd Even Linked List


You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...

Solution:
Two pointers: pre and tail, pre is the last odd number we visited, tail is the last even node we visited,
For example: after one round of loop, 1->3->2->4->5->null,
pre is node 3, tail is node 4, 
Set current node to tail.next which is 5,
tail.next=cur.next, 4->null,
tail=tail.next, tail =null
cur.next=pre.next, 5->2
pre.next=cur, 3->5
List: 1->3->5->2->4->null,
Time complexity: O(n) 

 public ListNode oddEvenList(ListNode head) {  
     if(head==null || head.next==null) return head;  
     ListNode pre=head;  
     ListNode tail=pre.next;  
     while(tail!=null && tail.next!=null){  
       ListNode cur=tail.next;  
       tail.next=cur.next;  
       tail=tail.next;  
       cur.next=pre.next;  
       pre.next=cur;  
       pre=cur;  
     }  
     return head;  
   }  
 }  

No comments:

Post a Comment