(Java)LeetCode-61. Rotate List
来源:互联网 发布:申请淘宝api接口流程 编辑:程序博客网 时间:2024/05/21 09:26
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
.
这道题也不是很难。循环右移一个链表。要注意的是循环的位数可能会超过链表长度。链表长度cnt 循环移位K位,实际上K = k % cnt
所以需要一个指针p2求出链表的长度,顺便找到最后一个节点,因为最后一个节点需要指向第一个节点.
还需要一个指针p1找到循环移动后的最后一个节点,它的下一个节点将成为第一个节点。
仔细点即可。代码如下:
public class Solution {public ListNode rotateRight(ListNode head, int k) {if(head == null || k == 0){ return head; } int cnt = 1; ListNode p2 = head; while(p2.next != null){ cnt++; p2 = p2.next; } k = k % cnt;ListNode pHead = head;ListNode p1 = head;for(int i = 0; i < cnt - k -1; i++){p1 = p1.next;}p2.next = pHead;pHead = p1.next;p1.next= null; return pHead; }}class ListNode {int val;ListNode next;ListNode(int x) { val = x; }}
0 0
- (Java)LeetCode-61. Rotate List
- 【leetcode】61. Rotate List【java】
- [LeetCode] 61. Rotate List java
- [Leetcode] Rotate List (Java)
- [LeetCode][Java] Rotate List
- leetcode:Rotate List 【Java】
- Rotate List leetcode java
- [leetcode]61. Rotate List@Java解题报告
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- jQuery实现遍历复选框
- 大富翁的游戏规则
- MyEclipse ci3中JSP乱码
- Srapy - Architecture overview【Data flow】
- 【深度学习:目标检测】CVPR 2016:目标检测领域的新进展
- (Java)LeetCode-61. Rotate List
- HDU 又见GCD
- HDU 5922 && 5924
- CODESYS 个性化设置
- KindEditor的使用
- Android群英传知识点回顾——第三章:Android控件架构与自定义控件详解
- ListView性能优化
- maven核心文件:pom.xml详解
- UVA 11987 Almost Union-Find(带删除的并查集)