Implement a function to reverse a linked list. The boilerplate code:
const reverseLinkedList = (list) => {
// your code
}
Set the new head to null, and list is the current node being reversed.
let prev = null;
let curr = list
For each node, save the next node temporarily, reverse the link and move curr and prev forward.
while(curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
When the loop ends, prev points to the new head of the reversed list. The final code:
const reverseLinkedList = (list) => {
// your code
let prev = null;
let curr = list;
while(curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next
}
return prev;
}
That's all folks!
Top comments (0)