Given a linked list, rotate the list to the right by k places, where k is non-negative
.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2Output: 4->5->1->2->3->NULLExplanation:rotate 1 steps to the right: 5->1->2->3->4->NULLrotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4Output: 2->0->1->NULLExplanation:rotate 1 steps to the right: 2->0->1->NULLrotate 2 steps to the right: 1->2->0->NULLrotate 3 steps to the right: 0->1->2->NULLrotate 4 steps to the right: 2->0->1->NULL
分析: 该题可以转化为从尾部向前数到第 k 个元素, 将该元素作为头节点, 同时将初始尾节点的下一个节点指向初始头节点。
此外如果链表长度为 0 或者链表长度与 k 相等时, 则链表实际上没有旋转交换位置。
l rdummy -> 1 -> 2 -> 3 -> 4 -> 5 -> NULL..l rdummy -> 1 -> 2 -> 3 -> 4 -> 5 -> NULL
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @param {number} k* @return {ListNode}*/var rotateRight = function(head, k) {const dummy = new ListNode(0)dummy.next = headlet count = 0let last = dummywhile (last.next) {last = last.nextcount++}if (count === 0 || count === k) return dummy.nextconst modK = k % countlet diff = modK + 1let l = dummylet r = dummywhile (diff--) {r = r.next}while (r) {r = r.nextl = l.next}last.next = dummy.nextdummy.next = l.nextl.next = nullreturn dummy.next}
19