DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Daniel Zaltsman
Daniel Zaltsman

Posted on

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

Top comments (0)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!