Tuesday, May 14, 2013

Rotate list(C++ code)

LeetCode Rotate List, Mar 28 '12
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

思路:新头在倒数第k个,需要把新头前面的node指向null,把链表尾巴指向旧头。要处理k大于表长度的情况。


  1. ListNode *rotateRight(ListNode *head, int k) {  
  2.   
  3.      if(!head) return NULL;  
  4.      if(k == 0) return head;  
  5.        
  6.      ListNode *tail = head, *prev = head;  
  7.   
  8.      int i = k;  
  9.   
  10.      //find last k+1-th elem and last elem.  
  11.   
  12.      while(k>0 &&tail->next != NULL){  
  13.   
  14.          tail = tail->next;   
  15.          k--;  
  16.   
  17.      }  
  18.   
  19.      //list length is i-k+1  
  20.   
  21.      if(tail->next == NULL) {  
  22.   
  23.         int listlen = i - k + 1;  
  24.   
  25.         k =listlen -  i%listlen-1;          
  26.   
  27.         while(k>0){prev = prev->next; k--;}  
  28.   
  29.     }  
  30.   
  31.      while(tail->next != NULL){  
  32.   
  33.           prev = prev->next;  
  34.   
  35.           tail = tail->next;  
  36.   
  37.      }  
  38.   
  39.      tail->next = head;  
  40.   
  41.      head = prev->next;  
  42.   
  43.      prev->next = NULL;  
  44.   
  45.      return head;           
  46.       
  47.  }  

No comments:

Post a Comment