您的位置:首页 > 其它

LeetCode 61. Rotate List

2016-04-12 23:21 281 查看
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
.

Need to pay attention to the K value. k = k % length

ListNode* rotateRight(ListNode* head, int k) {
if(!head || !head->next) return head;
ListNode* tmp = head;
int length = 0;
while(tmp) {
length++;
tmp = tmp->next;
}
k = k % length;           // k might be larger than the length of the linked list.
if(k == 0) return head;   // remember to check k value

ListNode* fast = head;
ListNode* slow = head;
while(k > 0) {
fast = fast->next;
k = k - 1;
}
while(fast && fast->next) {
slow = slow->next;
fast = fast->next;
}
ListNode* newHead = slow->next;
slow->next = NULL;
fast->next = head;
return newHead;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: