Rotate List
2014-06-10 14:43
183 查看
题目
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
方法
链表的旋转。public ListNode rotateRight(ListNode head, int n) { if (head == null) { return null; } ListNode node = head; int k = 0; while (node != null) { k++; node = node.next; } int len = k; n = n % len; if (n == 0) { return head; } ListNode start = new ListNode(0); start.next = head; ListNode pre = null; ListNode end = null; int i = 0; end = start; while (end.next != null) { end = end.next; if (pre != null) { pre = pre.next; } i++; if (i == n) { pre = start; } } if (i > n) { end.next = start.next; start.next = pre.next; pre.next = null; } return start.next; }
相关文章推荐
- Rotate List
- [LeetCode] Rotate List
- [LeetCode]Rotate List
- Rotate List
- Rotate List
- leetcode 61. Rotate List
- Rotate List
- 【leetcode每日一题】61.Rotate List
- leetcode:Rotate List
- Rotate List
- Rotate List
- LeetCode 61. Rotate List
- Leetcode 61. Rotate List
- [LeetCode] Swap Nodes in Pairs、Reverse Nodes in k-Group、Rotate List
- LeetCode - Rotate List
- Rotate List
- LeetCode OJ算法题(六十):Rotate List
- Rotate List
- Rotate List
- [LeetCode][Java] Rotate List