您的位置:首页 > 职场人生

[LeetCode] Rotate List

2014-01-04 04:34 288 查看
问题:

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
.
分析:
注意,当找到split point之后,两段子链表内的相对顺序是不变的。所以我的思路是,先把把链表连成一个环,然后找到相应的split point, 断开即可。

代码:

class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (k == 0) return head;
if (!head) return NULL;
if (!head->next) return head;
ListNode *tail = head;
int len = 1;
while (tail->next) {
len ++;
tail = tail->next;
}
tail->next = head;
k = k % len;
for (int i = 1; i < len - k; i ++) {
head = head->next;
}
ListNode *newHead = head->next;
head->next = NULL;
return newHead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 面试 leetcode