您的位置:首页 > 其它

leetcode 61:Rotate List

2015-11-19 19:47 211 查看
题目:

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
.
思路:
这题可以先确定链表数,然后找到需要截断的结点,将前半部分的最后一个结点next指向NULL,后半部分接到链表的前半部分前面。

注意边界条件:即k有可能大于等于size。

时间复杂度:O(n)

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