DEV Community

Akhil
Akhil

Posted on

2 3

Reverse a Linked List

"So you designed an algorithm that can sort integers in O(1) time? cool! But can you reverse a singly linked list?" - your interviewer

Reversing a linked list is one of those questions woes solution stares you on the face but it's a bit complex to code it.

Question: Given a single linked list, reverse it.

Let's go step by step on how one will solve it on paper physically.

Linked List:
Alt Text

Since if we reverse a linked list, the head will point towards end ie null.
1>Let's call that node prev.
2>Let's call the node we're currently on as curr for current
3>Since if we will point node's next towards a new node, we will lose its original next, let's call a node's original next as next.
Based on above our linked list looks like this :
Alt Text

Now point the curr's next to prev :
Alt Text

Now move prev to curr since for the next node the curr node will become prev:
Alt Text

And the next node becomes curr node, similar to initial condition:
Alt Text

Let's repeat the same process for all nodes.

Alt Text

Alt Text

Alt Text

Alt Text

Alt Text

Alt Text

Alt Text

At the end we return the prev pointer as the new head.

Alt Text

Now let's code it down as it is, step by step.

function reverseList(head) {
    var prev = null;                      // set prev to null
    while (head) {
        var next = head.next;             // set next as head's next 
        head.next = prev;                 // set pointer to prev
        prev = head;                      // move prev
        head = next;                      // move head
    }
    return prev;
}
Enter fullscreen mode Exit fullscreen mode

And that's it! As a challenge implement the same recursively!

github : https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/reverseLinkedList.js

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay