JSFiddle - React, Tailwind, and code Playground
JavaScript
class LinkedList {
constructor(value) {
this.head = {value};
}
getTail() {
let current = this.head;
while(current.next) current=current.next;
return current;
}
add(value) {
const tail = this.getTail();
tail.next = {value};
return this;
}
changeDirection(prev, current) {
const {next} = current;
current.next = prev;
if (next) {
this.changeDirection(current, next);
} else {
this.head = current;
}
}
reverse() {
const head = this.head;
if (!head.next) return this;
this.changeDirection(head, head.next);
delete head.next;
return this;
}
}
const list = new LinkedList(0);
list.add(1).add(2).add(3).reverse().add(-1);
console.log(list);