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 ,旋转列表最后 k 个元素至列表最前面。
关键是找到最后元素 lastOne 和 旋转后列表新的最后元素 newLastOne
1 ListNode* rotateRight(ListNode* head, int k) { 2 3 if (head == NULL) { 4 return NULL; 5 } 6 7 int n = 1; 8 ListNode* lastOne = head; 9 while (lastOne->next != NULL) { 10 n++; 11 lastOne = lastOne->next; 12 } 13 14 if (n == k) { 15 return head; 16 } 17 18 int firstNum = n - (k % n); 19 20 ListNode* newLastOne; 21 newLastOne = head; 22 for (int i = 1; i < firstNum; i++) { 23 newLastOne = newLastOne->next; 24 } 25 26 lastOne->next = head; 27 head = newLastOne->next; 28 newLastOne->next = NULL; 29 30 return head; 31 }