您的位置:首页 > 其它

【LeetCode】Rotate list

2015-05-12 22:57 148 查看

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: