Reversing a Linked List
class LinkedListNode {
constructor(value) {
this.value = value;
this.next = null;
}
printAll() {
let node = this;
while (node) {
console.log("current node.value is: ", node.value);
if (node.next === null) return;
node = node.next;
}
}
}
const chk = new LinkedListNode(10);
chk.next = new LinkedListNode(2);
chk.next.next = new LinkedListNode(5);
chk.next.next.next = new LinkedListNode(99);
console.log("chk", chk);
chk.printAll();
const reverse = (head) => {
let node = head;
let previous;
let temp;
while (node) {
temp = node.next;
node.next = previous;
previous = node;
node = temp;
}
return previous;
};
const head = new LinkedListNode(1);
head.next = new LinkedListNode(2);
head.next.next = new LinkedListNode(3);
const reversedHead = reverse(head);
console.log("reversed", reversedHead);
reversedHead.printAll();
class DoublyLinkedListNode {
constructor(value = null, prev = null) {
this.value = value;
this.next = null;
this.prev = prev;
}
printAll() {
let node = this;
while (node) {
console.log("current node.value is: ", node.value);
if (node.next === null) return;
node = node.next;
}
}
}
const head2 = new DoublyLinkedListNode(5);
head2.next = new DoublyLinkedListNode(10, head2);
head2.next.next = new DoublyLinkedListNode(15, head2.next);
console.log("double linked list", head2);
head2.printAll();