旋转链表。题意很简单,给一个linked list和一个数字k,请你对linked list向右rotate K次,输出rotate后的结果。例子
因为是单链表所以没法从右往左遍历链表。思路是将input先连成一个环,然后在新的head节点和其之前一个节点处断开即可。代码里面注意几个细节。
1. 算K的长度的时候,注意有可能K是大于链表长度len的,需要取余;
2. 22行的for loop是遍历到新的head节点之前的那个节点,然后再将其跟新的head断开;
时间O(n)
空间O(1)
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 };