Reverse Nodes in k-Group
Description
Given a linked list, reverse the nodes of a linked list k at a time and return its 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.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
Solution(javascript)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
const reverseKGroup = function(head, k) {
const swapPairs = function(head) {
if(!head || !head.next)
return head;
let r = head.next;
head.next = r.next
r.next = head;
head.next = swapPairs(head.next);
return r;
};
if(k === 1) return head;
if(k === 2) return swapPairs(head);
function getLen(head, l) {
if(!head) return l;
return getLen(head.next, l+1);
}
function reverseGroup(h, k, f) {
if(f === 0) return h;
let l = h;
let m = l.next;
let r = m.next;
for(let i = 0; i < k-2; i++) {
m.next = l;
l = m;
m = r;
r = r.next;
}
m.next = l;
h.next = reverseGroup(r, k, f-1);
return m;
}
return reverseGroup(head, k, Math.floor(getLen(head, 0)/k));
};