[leetcode] Rotate List
2014-06-26 15:17
309 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
https://oj.leetcode.com/problems/rotate-list/
思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。
思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。
思路1代码:
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
https://oj.leetcode.com/problems/rotate-list/
思路1:先遍历一遍求长度,然后从头再开始走k%len步,设置新的头尾节点,连接原来的头尾节点。
思路2:遍历求长度,将首尾连接,继续走到新的头尾,断开。
思路1代码:
public class Solution { public ListNode rotateRight(ListNode head, int n) { if (head == null) return null; int len = 0; ListNode p = head; while (p != null) { len++; p = p.next; } p = head; int i; n = n % len; if (n == 0) return head; for (i = 0; i < len - n - 1; i++) p = p.next; ListNode newTail = p; ListNode newHead = p.next; while (p.next != null) p = p.next; p.next = head; newTail.next = null; return newHead; } public static void main(String[] args) { ListNode head = ListUtils.makeList(1, 2, 3, 4, 5); ListUtils.printList(head); head = new Solution().rotateRight(head, 2); ListUtils.printList(head); } }
相关文章推荐
- [leetcode笔记] Rotate List
- LeetCode - 61 - Rotate List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- LeetCode 61. Rotate List2.
- 【一天一道LeetCode】#61. Rotate List
- 4.29 leetcode -29 rotate-list
- [LeetCode]problem 61. 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】61. Rotate List
- [LeetCode] Rotate List 解题报告
- [LeetCode] Rotate List
- Leetcode 61. Rotate List (Medium) (cpp)
- LeetCode 61 Rotate List