Rotate List
题目链接
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
.
<span style="font-size:14px;">/**
* 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(k <= 0 || head == NULL || head->next == NULL)//k取值<=0 , 链表中没有节点以及只有一个节点的情况。
return head;
//计算链表的长度,为了除了k>链表长度时候的情况。
ListNode* pfront = head;
int count = 0;
while(pfront != NULL)
{
count++;
pfront= pfront->next;
}
k = k % count;//处理k的值
//将链表向后移动,移动k位。
count = 0;
pfront = head;
while(pfront != NULL && count < k)
{
pfront = pfront->next;
count++;
}
//如果没有移动,则表示链表不需要reverse
if(pfront == head)
return head;
//设置节点p,用来记录需要从哪里开始截断链表
ListNode* p = head;
while(p->next!=NULL && pfront->next !=NULL)
{
p = p->next;
pfront = pfront->next;
}
//更改新的头指针
ListNode* newHead = p->next;
pfront->next = head;
p->next = NULL;
return newHead;
}
};</span>