标签:
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
.
[Solution]
tips: k might be large than list length, k = k % length
1 ListNode *rotateRight(ListNode *head, int k) 2 { 3 ListNode *fast = head, *slow = head; 4 int i, len = 0; 5 6 while (fast != NULL) 7 { 8 len++; 9 fast = fast->next; 10 } 11 12 if ((len <= 1) || ((k = k % len) == 0)) 13 return head; 14 15 fast = head; 16 for (i = 0; i < k; i++) 17 fast = fast->next; 18 while (fast->next != NULL) 19 { 20 fast = fast->next; 21 slow = slow->next; 22 } 23 fast->next = head; 24 head = slow->next; 25 slow->next = NULL; 26 27 return head; 28 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4340064.html