LeetCode | Rotate List
来源:互联网 发布:大学网络诋毁严正声明 编辑:程序博客网 时间:2024/06/06 04:57
一开始想错了,以为要在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;
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- Java 中使用 MySql以及一些Mysql 基本的命令
- Validation表单验证插件
- 深入浅出Dubbo(二)
- JavaWeb: 报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- POJ 1742 Coins
- LeetCode | Rotate List
- python开发简单爬虫:准备篇
- 深入浅出Dubbo(三)
- 跟风式、炒作式、跨业式三类创业者最容易挂掉
- Android实现跑马灯效果
- 51nod 1279 扔盘子
- 深入浅出Dubbo(四)
- 实现memcpy( )和memmove( )函数
- Windows快捷键