leetcode - Rotate List
2013-11-25 22:07 张汉生 阅读(159) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 ListNode *rotateRight(ListNode *head, int k) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 if (head == NULL || head->next ==NULL) 6 return head; 7 int size = 0; 8 ListNode * tmp = head; 9 while (tmp!=NULL){ 10 size++; 11 tmp = tmp->next; 12 } 13 k = k%size; 14 if (k<=0) 15 return head; 16 ListNode * rhead = NULL, * ltail = NULL, * rtail = NULL; 17 ListNode * itr = head; 18 int i = 0; 19 while (itr !=NULL){ 20 i++; 21 if (i==k){ 22 ltail = NULL; 23 rhead = head; 24 } 25 else if (i>k){ 26 ltail = rhead; 27 rhead = rhead->next; 28 } 29 rtail = itr; 30 itr = itr->next; 31 } 32 if (ltail!=NULL &<ail !=rtail) 33 ltail->next = NULL; 34 if (rhead!=NULL && rhead!=head){ 35 rtail->next = head; 36 return rhead; 37 } 38 return head; 39 } 40 };