您的位置:首页 > 其它

Leetcode132: Rotate List

2015-11-01 17:07 399 查看
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的值可能比链表的长度大,所以需要取余。再定义两个指针,一个超前另一个k步,然后同时向右走,直到前面的指针到达尾部,那么后面的指针所指的节点就是新的链表的尾部。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)
return head;
ListNode* l = head;
ListNode* r = head;
int n = 1;
while(l->next)
{
l = l->next;
n++;
}
k %= n;
l = head;
while(k)
{
r = r->next;
k--;
}
while(r->next)
{
r = r->next;
l = l->next;
}
r->next = head;
head = l->next;
l->next = NULL;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: