您的位置:首页 > 其它

【leetcode】Rotate List

2016-06-02 21:36 447 查看
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
.
思路:

将链表尾部和头部连起来,顺便算出链表长度len
计算k% len,把尾指针移动到位,然后断开

/**
* 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 == NULL)
return head;
ListNode* tail = head;
ListNode* newhead = head;
int len = 1;
while (tail->next != NULL)
{
tail = tail->next;
++len;
}
tail->next = head;
k %= len;
for (int i = 0; i < len - k; ++i)
{
tail = tail->next;
}
newhead = tail->next;
tail->next = NULL;
return newhead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: