Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Last active March 3, 2023 21:18
Show Gist options
  • Save optimistiks/cc1b04cd98b2e8d37736d92a4240e508 to your computer and use it in GitHub Desktop.
Save optimistiks/cc1b04cd98b2e8d37736d92a4240e508 to your computer and use it in GitHub Desktop.
Reverse the nodes of the linked list, k nodes at a time. If the number of nodes is not a multiple of k, the nodes left in the end will remain in their original order.
export function reverseLinkedList(head, k) {
let i = 0;
let resultHead = head;
// node preceding our sublist
let subPrev = null;
// node after our sublist
let subNext = head.next;
// start of our sublist
let start = head;
// end of our sublist
let end = head;
while (end) {
// if we are at the last element of a sublist
if (i === k - 1) {
// disconnect sublist from the rest of the list,
// remember the next node to connect to it later
subNext = end.next;
end.next = null;
if (subPrev) {
subPrev.next = null;
}
// at this point our sublist is [start, end]
// previous node is disconnected, and end is disconnected
let prev = null;
let curr = start;
while (curr) {
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// if it's our first reversal, we need to update resultHead
// that is going to be the head of our resulting list
if (!subPrev) {
resultHead = end;
}
// after reversal, our sublist is [end, start]
// reconnect
if (subPrev) {
subPrev.next = end;
}
start.next = subNext;
// at this point our sublist is reversed and reconnected back
// prepare variables for next iteration
i = 0;
subPrev = start;
start = subNext;
end = subNext;
} else {
++i;
end = end.next;
}
}
return resultHead;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment