61. Rotate List
题目:
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
.
链接:http://leetcode.com/problems/rotate-list/
题解:
先遍历一次链表,将尾部和头部相连,再进行移动。注意右移k步相当于prehead travel len - k步。
Time Complexity - O(n), Space Complexity - O(1)
public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || k == 0) return head; ListNode node = head; int len = 1; while(node.next != null){ node = node.next; len ++; } node.next = head; k %= len; for(int i = 0; i < len - k; i++) node = node.next; head = node.next; node.next = null; return head; } }
二刷:
主要思路还是把链表结成环。
- 先求出链表长度。
- 将链表结成环
- 计算k的合理范围。向右移动k位,就相当于从表头向左travel len - k个单位:
- 假如k < 0,那么说明向左移动,我们只需要计算-k % len就可以了
- 假如k > 0,我们需要把k变换为 len - k % len
- 接下来当k > 0的时候,我们从node继续往下travel, k--
- 第4步的遍历结束时,我们可以设置新的head = node.next,然后在此处断开环, node.next = null
- 最后返回head。
Java:
Time Complexity - O(n), Space Complexity - O(1)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null || head.next == null) { return head; } ListNode node = head; int len = 1; while (node.next != null) { node = node.next; len++; } node.next = head; if (k < 0) { k = -k % len; } else { k = len - k % len; } while (k > 0) { node = node.next; k--; } head = node.next; node.next = null; return head; } }
三刷:
看到k是non-negative的我就放心了。这里要注意我们结成环以后,在链表尾部寻找新的表头,需要移动的距离是 len - k % len。这样node.next就是新的表头。
Java:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null || k <= 0) return head; ListNode node = head; int len = 1; while (node.next != null) { node = node.next; len++; } node.next = head; k = len - k % len; while (k > 0) { node = node.next; k--; } head = node.next; node.next = null; return head; } }