Monday, January 5, 2015

Reverse Nodes in k-Group (LeetCode Linked List)

Question: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

Idea: Recursion. First locate the head of next run, the k+1'th node. Then reverse the first k nodes. After the reverse, let the k'th node's next point to the result of the next run.

Time: O(n) Space: O(n) (since we need a stack to store all the forgoing last pointers, e.g. at k, 2k, 3k)

Code:
 public class Solution {  
   public ListNode reverseKGroup(ListNode head, int k) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode nextHead=head;  
     for(int i=0;i<k;i++)  
     {  
       if(nextHead==null)  
         return head;  
       nextHead=nextHead.next;  
     }  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode pre=dummy.next;  
     ListNode cur=pre.next;  
     for(int i=0;i<k-1;i++)  
     {  
       pre.next=cur.next;  
       cur.next=dummy.next;  
       dummy.next=cur;  
       cur=pre.next;  
     }  
     pre.next=reverseKGroup(nextHead,k);  
     return dummy.next;  
   }  
 }  

No comments:

Post a Comment