【LeetCode】Rotate List
2014-11-18 19:07
387 查看
把倒数k个节点放到开始节点的前面,注意 n可能很大,需要对长度取余。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null || head.next == null)return head; int count = 0; int cur = 0; ListNode dummy = new ListNode(0); dummy.next = head; ListNode p = head; ListNode pre = head; while(p != null){ count++; p = p.next; } n = n % count; if(n == 0) return head; p = head; while(p != null){ cur++; pre = p; p = p.next; if(cur == count - n) break; } pre.next = null; ListNode newHead = p; while(p != null){ pre = p; p = p.next; } pre.next = dummy.next; return newHead; } }
相关文章推荐
- 【leetcode】Rotate List
- LeetCode:Rotate List
- Leetcode: Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- leetcode之Rotate List
- [LeetCode]--61. Rotate List
- leetcode Rotate List
- Leetcode rotate list
- leetcode 61. Rotate List
- [LeetCode] Rotate List
- leetcode JAVA Rotate List 难度系数3 3.20
- LeetCode 60 Rotate List
- [leetcode] Rotate List
- leetcode[61]Rotate List
- LeetCode 61 — Rotate List(C++ Java Python)
- leetcode之Rotate List
- leetcode 70: Rotate List
- 链表系列-把链表向右旋转k个位置LeetCode#61. Rotate List
- LeetCode(61) Rotate List