LeetCode | Rotate List
2016-07-31 20:57
363 查看
一开始想错了,以为要在k的位置旋转
其实是要循环滚动地推k次,比如
[1,2]
2
结果应当为[1,2],以为推一圈又回来了
而
[1,2]
3
则应当是[2,1]效果和1是一样的
于是加一个mod判断就好了
其实代码可以优雅一点
其实是要循环滚动地推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;
相关文章推荐
- [LeetCode61]Rotate List
- Leetcode 061 Rotate List
- [LeetCode] Swap Nodes in Pairs、Reverse Nodes in k-Group、Rotate List
- 【leetcode刷题笔记】Rotate List
- LeetCode 61 Rotate List
- 开始刷leetcode day32: Rotate List
- [Leetcode] Rotate List
- [Leetcode]Rotate List
- 【LeetCode with Python】 Rotate List
- LeetCode 61. Rotate List
- LeetCode 61. Rotate List
- [面试真题] LeetCode:Rotate List
- LeetCode 61. Rotate List
- LeetCode - Rotate List
- [leetcode刷题系列]Rotate List
- 【LeetCode】Rotate List
- 【LeetCode】61. Rotate List
- [Leetcode] Rotate List
- LeetCode---Rotate List
- LeetCode_Rotate List