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
ListNode* rotateRight(ListNode* head, int k) { if (head == NULL) {
return NULL;
} int n = ;
ListNode* lastOne = head;
while (lastOne->next != NULL) {
n++;
lastOne = lastOne->next;
} if (n == k) {
return head;
} int firstNum = n - (k % n); ListNode* newLastOne;
newLastOne = head;
for (int i = ; i < firstNum; i++) {
newLastOne = newLastOne->next;
} lastOne->next = head;
head = newLastOne->next;
newLastOne->next = NULL; return head;
}