Skip to content

Instantly share code, notes, and snippets.

@shaobos
Last active March 5, 2023 05:29
Show Gist options
  • Save shaobos/ea7a1b7fd5953202a28c1283298c3906 to your computer and use it in GitHub Desktop.
Save shaobos/ea7a1b7fd5953202a28c1283298c3906 to your computer and use it in GitHub Desktop.
Reverse linked list - Javascript
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(val) {
let node = new Node(val);
if (this.head === null) {
this.head = node;
} else {
let curr = this.head;
while (curr.next !== null) {
curr = curr.next;
}
curr.next = node;
}
}
reverse() {
// TODO: implement
}
print() {
let curr = this.head;
let str = "";
while (curr !== null) {
str += curr.val + " ";
curr = curr.next;
}
console.log(str);
}
}
let list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
console.log("Original list:");
list.print();
list.reverse();
console.log("Reversed list:");
list.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment