Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Reverse Linked List

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
504 upvotes
Asked in companies
CognizantMicrosoftSAP Labs

Problem statement

Given a singly linked list of integers. Your task is to return the head of the reversed linked list.

For example:
The given linked list is 1 -> 2 -> 3 -> 4-> NULL. Then the reverse linked list is 4 -> 3 -> 2 -> 1 -> NULL and the head of the reversed linked list will be 4.
Follow Up :
Can you solve this problem in O(N) time and O(1) space complexity?
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.

The only line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
Output Format :
For each test case, print the given linked list in reverse order in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
0 <= L <= 10^5
1 <= data <= 10^9 and data != -1

Time Limit: 1 sec
Sample Input 1 :
1
1 2 3 4 5 6 -1
Sample Output 1 :
6 5 4 3 2 1 -1
Explanation For Sample Input 1 :
For the first test case,  After changing the next pointer of each node to the previous node, The given linked list is reversed.
Sample Input 2 :
1
10 21 3 2 4 -1
Sample Output 2 :
4 2 3 21 10 -1
Hint

Try to reverse the Linked List node using recursion by finding the last node.

Approaches (5)
Brute Force

The brute force approach is to use recursion. First, we reach the end of the Linked List recursively and at last node, we return the last node, which becomes the new head of the partially reversed Linked List. While coming back from each recursion call we add the current node in the current recursion call to the last node of the partially reversed Linked List and assign the current node to null.

 

Steps:

 

  • We divide the linked list of N nodes into two parts. i.e head and rest of the Linked List with (N-1) nodes.
  • Now recursively reverse the (N-1) nodes of Linked List and return the head of this part i.e reverseHead. After the reversal, the next node of the head will be the last node of the reversed Linked List and the head next will be pointing to this node.
  • But for the complete reversal of the Linked List, the head should be the last node. So, we first find the last node of this reverseHead: Linked List then we do the following:
    • head.next = NULL
    • temp.next = head, where the temp is the last node of the reversed linked list.
  • At last, return the head pointer of the reversed Linked List i.e. return reverseHead.
Time Complexity

O(N ^ 2), where N is the number of nodes in the Linked List.

 

In the worst case, we are traversing the whole Linked List O(N) using recursion, and with each recursion call we are finding the last node of the reverse Linked List which takes O(N). Hence, the overall complexity will be O(N ^ 2).

Space Complexity

O(N), where N is the total number of nodes in the Linked List.

 

In the worst case, extra space is required for the recursion stack.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Reverse Linked List
All tags
Sort by
Search icon

Interview problems

2 Methods to Solve in C++

Solved by recursion and simple approach

#include <bits/stdc++.h>

 

void reverse(LinkedListNode<int>*&head, LinkedListNode<int>*prev,LinkedListNode<int>* curr){

    if(curr == NULL){

        // Set the head to the last node reached, which is the new head of the reversed list

        head = prev;

        return;

    }

    LinkedListNode<int>*forward = curr->next;   // Store the next node

    reverse(head,curr,forward);                               // Recursive call with updated pointers

    curr -> next = prev;                                             // Reverse the link

}


// Main function to reverse the linked list

LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head) 

{

    LinkedListNode<int>* prev = NULL;

    LinkedListNode<int> *curr = head;

    reverse(head,prev,curr);

    return head;


    //Second approach to solve.

    /*

    LinkedListNode<int>* prev = NULL;

    LinkedListNode<int> *curr = head;

    while(curr!= NULL){

        LinkedListNode<int>*next = curr->next;

        curr->next = prev;

        prev =curr;

        curr = next;

    }

    return prev;

    */

}

7 views
0 replies
1 upvote

Interview problems

C++

 

LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head) 

{

   LinkedListNode<int>* curr=head ,*prev=NULL,*next=NULL;

       while(curr !=NULL)

       {

          next=curr->next;

           curr->next=prev;

           prev=curr;

           curr=next;

       }

       return prev;

}

24 views
0 replies
0 upvotes

Interview problems

this is code in python

def reverseLinkedList(head):    prev = None    curr = head    while curr:        next_node = curr.next    # Store the next node        curr.next = prev         # Reverse the link        prev = curr              # Move prev to current node        curr = next_node         # Move to next node    return prev  # New head of the reversed list  

36 views
0 replies
0 upvotes

Interview problems

Reverse Linked List

LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head) 
{
    LinkedListNode<int>* prev =NULL;
    LinkedListNode<int>* ptr =head;
    LinkedListNode<int>* front =NULL;
    if(head == NULL || head->next ==NULL){
        return head;
    }
    while(ptr != NULL){
        front =ptr->next;
        ptr->next =prev;
        prev =ptr;
        ptr =front;
    }
    head =prev;
    return head;
}
116 views
0 replies
0 upvotes

Interview problems

reverse the linked list

LinkedListNode<int> * prev=NULL;

LinkedListNode<int> * curr=head;

LinkedListNode<int> * forword=NULL;

 

while(curr!=NULL){

forword=curr->next;

curr->next=prev;

prev=curr;

curr=forword;

}

return prev;

84 views
0 replies
0 upvotes

Interview problems

easy c++ code....

#include <bits/stdc++.h>

 

/****************************************************************

 

    Following is the class structure of the LinkedListNode class:

 

    template <typename T>

    class LinkedListNode

    {

    public:

        T data;

        LinkedListNode<T> *next;

        LinkedListNode(T data)

        {

            this->data = data;

            this->next = NULL;

        }

    };

 

*****************************************************************/

 

LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head) 

{

    if(head == nullptr ||head->next == nullptr)return head;

    // Write your code here

     LinkedListNode<int> *prev = nullptr;

     LinkedListNode<int> *curr = head;

     LinkedListNode<int> *forword = nullptr;

     while(curr!=nullptr){

         forword = curr->next;

         curr->next = prev;

         prev = curr;

         curr = forword;

 

     }

     return prev;

        

 

}

79 views
0 replies
0 upvotes

Interview problems

Easy Java Solution

public class Solution 

{

    public static LinkedListNode<Integer> reverseLinkedList(LinkedListNode<Integer> head) 

    {

        // Write your code here!

        LinkedListNode<Integer>prev=null;

        LinkedListNode<Integer>cur=head;

        LinkedListNode<Integer>nex=null;

        while(cur!=null){

            nex=cur.next;

            cur.next=prev;

            prev=cur;

            cur=nex;

        }

        return prev;

    }

}

78 views
0 replies
0 upvotes

Interview problems

Reverse LinkedList in java

public class Solution 

{

    public static LinkedListNode<Integer> reverseLinkedList(LinkedListNode<Integer> head) 

    {

        // Write your code here!

        LinkedListNode temp=head;

        LinkedListNode prev =null;

        LinkedListNode next=null;

        while(temp!=null){

            LinkedListNode front =temp.next;

            temp.next=prev;

            prev=temp;

            temp=front;

        }

        return prev;

    }

}

80 views
0 replies
0 upvotes

Interview problems

Reverse Linked List | JAVA

public class Solution 

{

    public static LinkedListNode<Integer> reverseLinkedList(LinkedListNode<Integer> head) 

    {

        // Write your code here!

        List<Integer> val = new ArrayList<>();

        if(head == null){

            return null;

        }

        while(head != null){

            val.add(head.data);

            head = head.next;

        }

        // System.out.println(val);

        LinkedListNode<Integer> d1 = new LinkedListNode<Integer>(val.get(val.size()-1));

        LinkedListNode<Integer> d2 = d1;

        for (int i = val.size()-2; i >=0; i--) {

            LinkedListNode<Integer> temp = new LinkedListNode<Integer>(val.get(i));

            d2.next = temp;

            d2 = temp;

        }

        return d1;

    }

}

48 views
0 replies
1 upvote

Interview problems

Reversal of Linked List Recursively and Iteratively

#include <bits/stdc++.h>

/****************************************************************

    Following is the class structure of the LinkedListNode class:

    template <typename T>
    class LinkedListNode
    {
    public:
        T data;
        LinkedListNode<T> *next;
        LinkedListNode(T data)
        {
            this->data = data;
            this->next = NULL;
        }
    };

*****************************************************************/

LinkedListNode<int> *reverseLinkedList(LinkedListNode<int> *head) 
{
    if(head == nullptr || head->next == nullptr) return head;

    LinkedListNode<int> *newHead = reverseLinkedList(head->next);

    LinkedListNode<int> *front = head->next;

    front->next = head;

    head->next = nullptr;

    return newHead;
}
168 views
0 replies
1 upvote
Full screen
Console