Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list’s nodes, only nodes themselves may be changed.
Example:
1 2
Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5]
/* * @Description: 链表中的节点每k个一组翻转 * @Author: libk * @Github: https://github.com/libk */ /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode}head * @param {number}k * @return {ListNode} */ const reverseKGroup = function (head, k) { let tail = head for (let i = 0; i < k; i++) { if (tail === null) { return head } tail = tail.next }
let pre = null let cur = head while (cur !== tail) { let temp = cur.next cur.next = pre pre = cur cur = temp } head.next = reverseKGroup(tail, k) return pre }
/** * @param {ListNode}head * @param {number}k * @return {ListNode} */ let reverseKGroup2 = function (head, k) { let length = getLength(head) let newHead = head for (let i = 1; (i + k - 1) <= length; i += k) { newHead = reverseBetween(newHead, i, i + k - 1) } return newHead }
functiongetLength (head) { let n = 0 let cur = head while (cur !== null) { cur = cur.next n++ } return n }
functionreverseBetween (head, left, right) { let dummy = new ListNode(-1) dummy.next = head let pre = dummy let cur = head for (let i = 1; i < left; i++) { pre = cur cur = cur.next } for (let j = left; j < right; j++) { let temp = cur.next cur.next = temp.next temp.next = pre.next pre.next = temp } return dummy.next }