Rotate List
来源:互联网 发布:巅峰软件下载 编辑:程序博客网 时间:2024/06/03 11:47
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题目的意思就是将倒数K个数翻转到前面去
用正常的思路我试过没问题(先遍历求得总长度,然后再遍历求3的位置和5的位置),这里介绍一种巧妙地方法
设两个指针p1,p2,p1先走k个位置,然后p1,p2同时走直至p1下一个位置为NULL,这样p2到3的位置,p1在5的位置,即无需第一遍求长度(但是在leetcode中会出现k值大于长度,这就导致必须求长度,所以这种方法的优点体现不出来,但是思想很不错)
测试通过的代码
ListNode* rotateRight(ListNode* head, int k) { if(head==NULL||k==0) return head; ListNode * p3=head; int len=0; while(p3) { p3=p3->next; len++; } k=k%len; if(k==0) return head; ListNode *p1=head; ListNode *p2=head; for(int i=0;i<k;i++) { p1=p1->next; if(p1==NULL) return head; } while(p1->next!=NULL) { p1=p1->next; p2=p2->next; } ListNode * NHead=p2->next; p1->next=head; p2->next=NULL; return NHead; }
阅读全文
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- springMVC @RestController和@Controller的区别
- 如何在Anaconda中实现多版本python Spyder共存
- EL表达式总结和使用
- Dell服务器远程卡java连接失败
- 字符串全排列问题(递归解决有重复字符问题)
- Rotate List
- 将1-100的奇数存入数组
- Java中的String详解
- Android Gradle 构建环境
- iOS动态性(一) 一行代码实现iOS序列化与反序列化(runtime)
- web本地存储--localStorage和sessionStorage
- Linux 系统缓存机制
- 【BZOJ】 1610 [Usaco2008 Feb]Line连线游戏 计算几何
- three.js模型搭建与地图的3D可视化参考资源