LeetCode Rotate List
来源:互联网 发布:宝洁 波士顿矩阵分析 编辑:程序博客网 时间:2024/05/16 17:13
题目
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个数,
注意点:
1、k可以是0
2、链长可以是0(空链)
3、k可以大于链的长度,这样将是循环右移
代码:
/*******************************************************************struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*******************************************************************/
class Solution {public: ListNode *rotateRight(ListNode *head, int k) {if(k==0||head==NULL)//空链或者右移0次return head; ListNode *back=head,*new_head=head,*new_back=head;//链尾,新的头,新的尾int len=1;//链长度while(new_head->next!=NULL)//由链长计算有效右移位数{len++;new_head=new_head->next;}k%=len;if(k==0)return head;for(int i=0;i<k;i++)//获取新的头尾位置back=back->next;while(back->next!=NULL){back=back->next;new_back=new_back->next;}new_head=new_back->next;//修改链back->next=head;new_back->next=NULL;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
- ECharts使用心得
- 二分图匹配
- 在MySQL字段中使用逗号分隔符
- 音量键唤醒屏幕--解决电源键坏掉的情况
- windows下批量删除svn文件
- LeetCode Rotate List
- 同余定理
- OneThink自动验证设置之自定义错误代码
- Memcached - 几款java客户端对比
- Nginx细节优化总结
- 匈牙利算法
- jQuery日历插件CLNDR.js
- GreenDao开源ORM框架浅析
- OCP 1Z0 053 145(同135)