DEV Community

loading...
Cover image for LinkedList Questions: Reverse a Linked List - Recursive version

LinkedList Questions: Reverse a Linked List - Recursive version

Kathan Vakharia
DS-Algo Tenderfoot | Computer Scientist | Aspiring Gopher | DataScience Enthusiast | Python & C++ ๐Ÿ’•
ใƒป2 min read

In this series of posts, I will discuss coding questions on the LinkedList Data structure.
The posts in this series will be organized in the following way,

  1. Question Link โ“
  2. Possible Explanation ๐Ÿ“
  3. Documented C++ Code ๐Ÿงน
  4. Time and Space Complexity Analysis โŒ›๐ŸŒŒ

The Question

Given theย headย of a singly linked list, reverse the list, and return the reversed list.

https://leetcode.com/problems/reverse-linked-list/

๐Ÿ’ก Give yourself at least 15-20 mins to figure out the solution :)

Explanation

Its bit tricky so pay your atmost attention,

The idea is to make current node's successor( curโ†’next ) point to current and there by reversing the list. (Here, we are under assumption that the list after current node is already reversed ).

Lastly, we will return the last node's pointer as the new head of our reversed linkedlist.

See the recursion animation to make things more clear,

C++ Code

Definition of Linked List

//Definition for singly-linked list.
struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

Enter fullscreen mode Exit fullscreen mode

Solution

ListNode *reverseList(ListNode *head)
    {
        /*
        *Approach
            -Let's say list is n0 -> n1 ->... "nk" -> nk+1 -> ...n->null
            -when we are on nk, we assume nk+1 <-...n i.e. the list ahead is reversed 
        */

       //* When 1. list contains 0 or 1 node, 
       //* 2. head is pointing last node
        if (head == nullptr || head->next == nullptr)
            return head;

        ListNode *last = reverseList(head->next);

        //note: To make sure this works, we need to make sure:
        //> head->next and head exits (base condition)
        head->next->next = head; //! crux

        head->next = nullptr;

        return last;
    }
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Time Complexity: O(n)

We will visit every node once.

Space Complexity: O(n)

The size of recursion stack as we will go n levels deep.

References:

https://leetcode.com/problems/reverse-linked-list/solution/

Discussion (0)