[LeetCode] 61. Rotate List
Given the head
of a linked list, rotate the list to the right by k
places.
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints:
- The number of nodes in the list is in the range
[0, 500]
. -100 <= Node.val <= 100
0 <= k <= 2 * 109
旋转链表。
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
题意很简单,给一个 linked list 和一个数字 k,请你对 linked list 向右 rotate K 次,输出 rotate 后的结果。因为是单链表所以没法从右往左遍历链表。思路是将 input 先连成一个环,然后在新的 head 节点和其之前一个节点处断开即可。代码里面注意几个细节。
1. 算 K 的长度的时候,注意有可能 K 是大于链表长度 len 的,需要做取模操作
2. 22 行的 for loop 是遍历到新的 head 节点之前的那个节点,然后再将其跟新的 head 断开
跑一个例子
1 - 2 - 3 - 4 - 5, k = 2
先移动到链表末端,得到长度 len = 5
1 - 2 - 3 - 4 - 5
|______________|
h
h
将链表末端再连到 head 节点,形成一个环
因为需要往右rotate 2次,所以实际上是要将 head 指针往后移动 len - k 次,这样 head 指针会在新的 head 之前的一个节点上(4)。此时新的 head 节点是 head.next
最后将 4 和 5 之间的连接断开即可
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {ListNode} head 3 * @param {number} k 4 * @return {ListNode} 5 */ 6 var rotateRight = function(head, k) { 7 // corner case 8 if (head == null || head.next == null) { 9 return head; 10 } 11 12 // normal case 13 let len = 1; 14 let index = head; 15 while (index.next !== null) { 16 index = index.next; 17 len++; 18 } 19 index.next = head; 20 21 // loop again 22 for (let i = 1; i < len - (k % len); i++) { 23 head = head.next; 24 } 25 let res = head.next; 26 head.next = null; 27 return res; 28 };
Java实现
1 class Solution { 2 public ListNode rotateRight(ListNode head, int k) { 3 // corner case 4 if (head == null || head.next == null) { 5 return head; 6 } 7 // get the length 8 ListNode index = head; 9 int len = 1; 10 while (index.next != null) { 11 index = index.next; 12 len++; 13 } 14 15 index.next = head; 16 for (int i = 1; i < len - k % len; i++) { 17 head = head.next; 18 } 19 ListNode res = head.next; 20 head.next = null; 21 return res; 22 } 23 }
相关题目