61. Rotate List
来源:互联网 发布:通达信的软件 编辑:程序博客网 时间:2024/06/07 06:55
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.
分析:
先令一个指针node跑到最后的一个节点(非NULL)处;
让node的下一个指针指向头结点形成环形单链表;
然后就是计算要遍历的次数。这里分为三种情况:
1.k>n: k=k%n>0;
2.k
/** * 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(!head) return NULL; ListNode* node=head; int n=1;//这里必须为1,否则后面k=k%n的时候不对 while(node->next){ node=node->next; n++; } node->next=head; if(k %= n) { int n1=n-k;//循环次数 while(n1--!=0) node=node->next; } ListNode* newhead=head; newhead=node->next; node->next=NULL; return newhead; }};
阅读全文
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- servlet的映射路径
- banner轮播
- 牛客网---2016---去哪儿文本嗅探
- 图论总结(持续更新)
- Hadoop之namenode-yellowcong
- 61. Rotate List
- Java反序列化时报异常java.io.EOFException
- <context:component-scan>使用详情
- iOS TranslationZoom(平移 缩放 弹性)~demo
- hdu 6119 小小粉丝度度熊(交叉区间去重)
- python 文件操作
- java的http请求的书写
- 初学反射,实现数据库到对象的关系映射,简陋版!
- nginx 负载均衡时,一台tomcat宕机时的问题 自动切换