Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wataruoguchi/4ed96eb7fc91f8b4954b0ebd48222b38 to your computer and use it in GitHub Desktop.
Save wataruoguchi/4ed96eb7fc91f8b4954b0ebd48222b38 to your computer and use it in GitHub Desktop.
// https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
class Node {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
function printList(head) {
let tmp = head;
let arr = [];
while (tmp) {
arr.push(tmp.val);
tmp = tmp.next;
}
return arr;
}
function reverseK(head, K) {
let tmp = head;
let next;
let prev;
let count = 0;
while (tmp && count < K) {
next = tmp.next;
tmp.next = prev;
prev = tmp;
tmp = next;
count++;
}
if (next) {
head.next = reverseK(next, K);
}
return prev;
}
const ex1Head = new Node(1, new Node(2,
new Node(3, new Node(4, new Node(5, new Node(6, new Node(7, new Node(8))))))));
const res = reverseK(ex1Head, 3);
console.log(printList(res).join(',') === '3,2,1,6,5,4,8,7');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment