Last active
June 28, 2021 14:27
-
-
Save danny-andrews/7a647eecfd5fa1fe95eebcc335ce861d to your computer and use it in GitHub Desktop.
Linked List Reversal Prompt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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