DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 51

Implement a function to reverse a linked list. The boilerplate code:

const reverseLinkedList = (list) => {
    // your code
}
Enter fullscreen mode Exit fullscreen mode

Set the new head to null, and list is the current node being reversed.

let prev = null;
let curr = list
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)