[Leetcode] Rotate List
来源:互联网 发布:linux上telnet 编辑:程序博客网 时间:2024/06/15 04:53
题目:循环单链表。
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可能很大,实际移动的k=k%length,具体过程在程序中注释。
ListNode *rotateRight(ListNode *head, int k) { if(head ==NULL || k==0) return head; ListNode *x=head;int i=1;for(i=1; x ->next !=NULL; i++) //计算链表长度x=x->next ;ListNode *last=x;//保存最末尾节点k=i-k%i;//分割点位置if(k == i) return head; //等于原长不需移动x=head;for(; k<i&& k>1; k--)//找到分割点x=x->next;last->next=head;//最尾节点链接头结点head=x->next;//下一个点为新头结点x->next=NULL;//截断当前点return 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
- make sure this plugin is properly configured & 任务管理器查看框
- 菜鸟的安卓实习之路----android广播(2)
- Runtime(三)
- 详解为QT Webkit编写插件案例实现
- 学习OpenGL简单总结
- [Leetcode] Rotate List
- 优先队列用法
- informatical lookup的使用详解
- Linux 大文件分割split与合并cat使用方法
- 关于手机设置中的RAM及内部存储空间
- 华侨大学总裁班管理分享:企业十二种最可怕的隐形成本
- Runtime(四)
- mongose链接数据库与批插入
- poj1270Following Orders(拓扑排序+dfs回溯)