您的位置:首页 > 其它

leetcode 61. Rotate List

2016-03-20 12:43 344 查看
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
.

class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (k == 0)
return head;
ListNode*p = head;
int len = 0;
while (p != NULL)
{
p = p->next;
len++;
}
if (len == 0||len==1)
return head;
k = k%len;
if (k == 0)
return head;
p = head; int kk = 1;
while (kk != len - k)
{
p = p->next;
kk++;
}
ListNode*p1 = p->next, *p2 = p->next;
while (p1->next != NULL)
p1 = p1->next;
p1->next = head;
p->next = NULL;
head = p2;
return head;
}
};

accepted
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: