Leetcode: Rotate List
2014-06-23 23:28
267 查看
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.
Anaylisis: Linked List题目的做法其实比较固定,就是Runner Technique(Two pointer) 方法加上 Dummy Node(设置一个head之前的虚假节点)两种方法,这道题就这样搞一搞就出来了。
需要注意的是:处理null 输入需要特别考虑,然后,需要找到新的linked list的头
第二遍做法:注意15行需要特别处理,wrap up了之后n=0的情况
public class Solution { public ListNode rotateRight(ListNode head, int n) { if (head == null) return null; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode cursor = dummy; ListNode walker = dummy; ListNode runner = dummy; int count = 0; while (cursor.next != null) { cursor = cursor.next; count ++; } n %= count; if (n == 0) return head; while (n > 0) { runner = runner.next; n--; } while (runner.next != null) { runner = runner.next; walker = walker.next; } dummy.next = walker.next; walker.next = runner.next; runner.next = head; return dummy.next; } }
相关文章推荐
- 【leetcode】Rotate List
- Leetcode 61. Rotate List
- leetcode第一刷_Rotate List
- leetcode 61. Rotate List
- leetcode:Rotate List
- leetcode_061 Rotate List
- [LeetCode] Rotate List
- 《leetCode》:Rotate List
- LeetCode | Rotate List
- leetcode - 61.Rotate List
- [Leetcode]@python 61. Rotate List
- leetcode 061 Rotate List
- [leetcode]61. Rotate List
- LeetCode: Rotate List
- 43 leetcode - Rotate List
- leetcode: Rotate List
- [LeetCode]Rotate List
- LeetCode——Rotate List
- Leetcode 61. Rotate List
- LeetCode——Rotate List