您的位置:首页 > 其它

leetcode---rotate-list---链表

2017-10-25 18:47 295 查看
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given1->2->3->4->5->NULLand k =2,

return4->5->1->2->3->NULL.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverse(ListNode *head)
{
if(!head || !head->next)
return head;

ListNode *nextH = head->next;
ListNode *newH = reverse(nextH);
nextH->next = head;
head->next = NULL;
return newH;
}
ListNode *rotateRight(ListNode *head, int k)
{
if(!head || k == 0)
return head;

int n = 0;

ListNode *p = head;
ListNode *last = head;
while(p)
{
n++;
last = p;
p = p->next;
}

k = k % n;
if(k == 0)
return head;

n = n - k;
int i = 1;
p = head;
while(p && i<n)
{
i++;
p = p->next;
}

ListNode *next = p->next;
p->next = NULL;
last->next = head;
return next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: