Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Last active June 28, 2021 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/7a647eecfd5fa1fe95eebcc335ce861d to your computer and use it in GitHub Desktop.
Save danny-andrews/7a647eecfd5fa1fe95eebcc335ce861d to your computer and use it in GitHub Desktop.
Linked List Reversal Prompt
// Given the linked list implementation below
// write a method which reverses the list.
function ListNode(data) {
this.data = data;
this.next = null;
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToTail(data) {
const node = new ListNode(data);
if (!this.tail) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
return node;
}
traverse(fn) {
let node = this.head;
while (node) {
fn(node.data);
node = node.next;
}
}
// For debugging
print() {
return this.traverse(console.log);
}
reverse() {
// YOUR CODE HERE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment