Rotate List
/** Definition for singly-linked list. */
#include <iostream>
using namespace std;
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;
}
//求length
ListNode *p=head;
ListNode *pEnd=p;//pEnd指向最后一个非NULL节点
int length=0;
while (p!=NULL) {
length++;
pEnd=p;
p=p->next;
}
ListNode *pCur=head;
ListNode *firstEnd=NULL;
int startCur=length-k%length;//开始移动的位置
//边界条件
if (k%length==0||length==1) {
return head;
}
//找到第一段结尾处
while (startCur) {
firstEnd=pCur;
pCur=pCur->next;
startCur--;
}
pEnd->next=head;
firstEnd->next=NULL;
return pCur;
}
};
int main(){
ListNode *p=new ListNode(1);
p->next=new ListNode(2);
int k=1;
Solution so;
ListNode *res= so.rotateRight(p, k);
cout<<res->val<<res->next->val<<endl;
}