class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
get_list() {
result = "";
temp = this;
while (temp !== null) {
result += temp.value + " ";
temp = temp.next;
}
return result;
}
};
const reverse_every_k_elements = function (head, k) {
let curr = head
let prev = null
while (true) {
let i = 0
// after reversing, this ref to curr will be the last node of the section
const lastNodeOfCurrRevSection = curr
const lastNodeOfLastRevSection = prev
// reverse k nodes
while (curr !== null && i < k) {
const next = curr.next
curr.next = prev
prev = curr
curr = next
i += 1
}
const firstNodeOfCurrentRevSection = prev
if (lastNodeOfLastRevSection === null) {
// start of the list, set new head
head = firstNodeOfCurrentRevSection
} else {
// link the last reversed list with the one we just reversed
lastNodeOfLastRevSection.next = firstNodeOfCurrentRevSection
}
// link the current reversed list with the next unreversed section
lastNodeOfCurrRevSection.next = curr
// break if we reached the end of the list
if (curr === null) {
break
}
// pass the last node of the list we just reversed
// to the next iteration
prev = lastNodeOfCurrRevSection
}
return head
}
head = new Node(1)
head.next = new Node(2)
head.next.next = new Node(3)
head.next.next.next = new Node(4)
head.next.next.next.next = new Node(5)
head.next.next.next.next.next = new Node(6)
head.next.next.next.next.next.next = new Node(7)
head.next.next.next.next.next.next.next = new Node(8)
console.log(`Nodes of original LinkedList are: ${head.get_list()}`)
console.log(`Nodes of reversed LinkedList are: ${reverse_every_k_elements(head, 3).get_list()}`)
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Reverse every K-element Sub-list (medium) - Grokking the Coding Interview: Patterns for Coding Questions
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Reverse every K-element Sub-list (medium) - Grokking the Coding Interview: Patterns for Coding Questions
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Reverse every K-element Sub-list (medium) - Grokking the Coding Interview: Patterns for Coding Questions