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大于结点数)
特殊输入测试(输入的链表结点头指针为NULL,k=0)
/**
* 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 || k==0) return head;
int n=0;
ListNode *pNode=head;
while(pNode!=NULL)
{
pNode=pNode->next;
n++;
}
if(k>=n) k %= n;
if(k==0) return head;
pNode=head;
for(int i=0; i<k; ++i)
{
pNode=pNode->next;
}
ListNode *sNode=head;
while(pNode->next != NULL)
{
pNode=pNode->next;
sNode=sNode->next;
}
ListNode *tmphead=sNode->next;
pNode->next=head;
sNode->next=NULL;
return tmphead;
}
};