Reverse a Linked List

danimal92

Daniel Zaltsman

Posted on June 19, 2020

Reverse a Linked List

This will be my first post of many as I navigate through leetcode, sharing and explaining my solutions!

This one, however, is more of a utility question. Basically you know it or you don't.

If you don't know what a linked list is, the short explanation is a linear data structure that contains a head, which contains information, and a reference to the next object. If you want to read more on linked lists, check out my posts on data structures!

Reversing a linked list

This portion is for those who are already aware of what linked lists and how they're implemented. The question is simple enough: Reverse a singly linked list.

I know what you're thinking: WHAT?! BUT HOW?!

That's what I thought. The key is pointer variables. I'll show you the code first and explain how it works.

var reverseList = function(head) {
    let prev = null
    let current = head
    let next = head

    while(current !== null){
        next = current.next
        current.next = prev
        prev = current
        current = next
    }
    return prev
};

This may be a bit helpful, but let's dive into it.
As you can see, we have three variables: prev, current, and next outside of a while loop.

Prev is set to null, current is set to the head of the linked list as well as next.

While current does not equal null, next becomes the node after the current one. The reference to the next node now becomes prev, which is null. prev now becomes current, which is the head. And current becomes the next node.

If we were using 1->2->3->4->5 as our linked list, next moved on from 1 to 2, the reference or arrow from 1 goes to null, prev becomes 1, and current becomes 2 along with next.

Do you see the pattern?

What should happen next is: next becomes 3, the reference or arrow from 2 now points to 1, prev becomes 2, and current becomes 3. This continues until current becomes null. Here's a nifty gif to help visualize this:

Reverse a singly linked list

💖 💪 🙅 🚩
danimal92
Daniel Zaltsman

Posted on June 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related