您的位置:首页 > 其它

Leetcode -- Rotate List

2015-08-15 09:40 155 查看
题目:

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个node旋转到链表的开头。若k大于链表的长度,则应该先进行求余,再进行链表旋转。

思路:

1)计算链表的长度,计算在第几个点,旋转链表

2)找到该节点,将该节点的上一个节点的next设置为NULL,将链表最后一个节点的next设置为head。

代码:

ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
ListNode* l = head;
ListNode* last;
ListNode* p;
int len = 0;
int times = 0;
while(l)
{
len ++;
last = l;
l = l->next;
}
k = k%len;
if (k != 0)
{
l = head;
for(int i = 1; i < (len - k); i++)
{
l = l->next;
}
p = l ->next;
l->next = NULL;
last->next = head;
return p;
}
return head;
}


leetcode的测试用例,总是存在一个输入为空的情况,记住要额外处理一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表