Question
Method1
Using two pointers to make the distance equal k%ListNode.length()//This is got from a loop
/**
* 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)
return head;
int list_len=0;
ListNode *pList=head;
for(;pList;pList=pList->next)
++list_len;
if(list_len<=1)
return head;
k=k%list_len;
if(k==0)
return head;
ListNode *pre,*lst;
pre=lst=head;
int dis=0;
while(lst->next){
if(dis!=k){
++dis;
lst=lst->next;
}else{
lst=lst->next;
pre=pre->next;
}
}
ListNode *tmp=pre->next;
pre->next=NULL;
lst->next=head;
return tmp;
}
};
Method2
Using a vector<ListNode*>
to make find postion of new head easily.
/**
* 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) {
vector<ListNode*> tmp;
int list_len=0;
ListNode *pList=head;
for(;pList;pList=pList->next)
tmp.push_back(pList);
list_len=tmp.size();
if(list_len<=1)
return head;
k=k%list_len;
if(k==0)
return head;
ListNode *resHead=tmp[list_len-k];
tmp[list_len-1]->next=head;
tmp[list_len-1-k]->next=NULL;
return resHead;
}
};