您的位置:首页 > 其它

LeetCode | Rotate List

2016-07-31 20:57 363 查看
一开始想错了,以为要在k的位置旋转

其实是要循环滚动地推k次,比如

[1,2]

2

结果应当为[1,2],以为推一圈又回来了



[1,2]

3

则应当是[2,1]效果和1是一样的

于是加一个mod判断就好了

class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//空或左侧没有链
if(head==NULL || head->next==NULL) return head;
ListNode* new_head;
ListNode root(head->val-1);
root.next=head;

ListNode* t=head;
int count=0;
while(t!=NULL){
count++;
t=t->next;
}
//找出要推多少次
k%=count;
if(k==0) return head;
k=count-k;

ListNode* pre=&root;
t=head;
for(count=0;t!=NULL;pre=pre->next,t=t->next,count++){
if(count==k){
new_head=t;
// //获取最后一个节点
ListNode* temp=t;
while(temp->next!=NULL) temp=temp->next;

//连接尾部到头部
temp->next=root.next;

pre->next=NULL;
break;
}
}
return new_head;
}
};


其实代码可以优雅一点

//空或左侧没有链
if(head==NULL || head->next==NULL) return head;
ListNode* new_head;

ListNode* t=head;
int count=1;
while(t->next!=NULL){
count++;
t=t->next;
}
//找出要推多少次
k%=count;
if(k==0) return head;
k=count-k;

//连接尾部到头,在前面遍历到最后的时候,就可以保留这个指针
t->next=head;

for(count=0;t->next!=NULL;t=t->next,count++){
if(count==k){
new_head=t->next;
t->next=NULL;
break;
}
}
return new_head;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: