您的位置:首页 > 其它

【LeetCode】Rotate List

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