[Expected Approach] Using Iterative Method - O(n) Time and O(1) Space
The idea is to reverse the links of all nodes using three pointers:
prev: pointer to keep track of the previous node
curr: pointer to keep track of the current node
next: pointer to keep track of the next node
Starting from the first node, initialize curr with the head of linked list and next with the next node of curr. Update the next pointer of curr with prev. Finally, move the three pointer by updating prev with curr and curr with next.
Follow the steps below to solve the problem:
Initialize three pointers prev as NULL, curr as head, and next as NULL.
Iterate through the linked list. In a loop, do the following:
Store the next node, next = curr -> next
Update the next pointer of curr to prev, curr -> next = prev
Update prev as curr and curr as next, prev = curr and curr = next
C++
// Iterative C++ program to reverse a linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Given the head of a list, reverse the list and // return the head of reversed listNode*reverseList(Node*head){// Initialize three pointers: curr, prev and nextNode*curr=head,*prev=nullptr,*next;// Traverse all the nodes of Linked Listwhile(curr!=nullptr){// Store nextnext=curr->next;// Reverse current node's next pointercurr->next=prev;// Move pointers one position aheadprev=curr;curr=next;}// Return the head of reversed linked listreturnprev;}voidprintList(Node*node){while(node!=nullptr){cout<<" "<<node->data;node=node->next;}}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);cout<<"Given Linked list:";printList(head);head=reverseList(head);cout<<"\nReversed Linked List:";printList(head);return0;}
C
// Iterative C program to reverse a linked list#include<stdio.h>structNode{intdata;structNode*next;};// Given the head of a list, reverse the list and return the// head of reversed liststructNode*reverseList(structNode*head){// Initialize three pointers: curr, prev and nextstructNode*curr=head,*prev=NULL,*next;// Traverse all the nodes of Linked Listwhile(curr!=NULL){// Store nextnext=curr->next;// Reverse current node's next pointercurr->next=prev;// Move pointers one position aheadprev=curr;curr=next;}// Return the head of reversed linked listreturnprev;}voidprintList(structNode*node){while(node!=NULL){printf(" %d",node->data);node=node->next;}}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);printf("Given Linked list:");printList(head);head=reverseList(head);printf("\nReversed Linked List:");printList(head);return0;}
Java
// Iterative Java program to reverse a linked listclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}// Given the head of a list, reverse the list and return the// head of reversed listclassGfG{staticNodereverseList(Nodehead){// Initialize three pointers: curr, prev and nextNodecurr=head,prev=null,next;// Traverse all the nodes of Linked Listwhile(curr!=null){// Store nextnext=curr.next;// Reverse current node's next pointercurr.next=prev;// Move pointers one position aheadprev=curr;curr=next;}// Return the head of reversed linked listreturnprev;}// This function prints the contents// of the linked list starting from the headstaticvoidprintList(Nodenode){while(node!=null){System.out.print(" "+node.data);node=node.next;}}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);System.out.print("Given Linked list:");printList(head);head=reverseList(head);System.out.print("\nReversed Linked List:");printList(head);}}
Python
# Iterative Python program to reverse a linked listclassNode:def__init__(self,newData):self.data=newDataself.next=None# Given the head of a list, reverse the list and return the# head of reversed listdefreverseList(head):# Initialize three pointers: curr, prev and nextcurr=headprev=None# Traverse all the nodes of Linked ListwhilecurrisnotNone:# Store nextnextNode=curr.next# Reverse current node's next pointercurr.next=prev# Move pointers one position aheadprev=currcurr=nextNode# Return the head of reversed linked listreturnprevdefprintList(node):whilenodeisnotNone:print(f" {node.data}",end="")node=node.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)print("Given Linked list:",end="")printList(head)head=reverseList(head)print("Reversed Linked List:",end="")printList(head)
C#
// Iterative C# program to reverse a linked listusingSystem;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}// Given the head of a list, reverse the list and return the// head of reversed listclassGfG{staticNodeReverseList(Nodehead){// Initialize three pointers: curr, prev and nextNodecurr=head;Nodeprev=null;Nodenext;// Traverse all the nodes of Linked Listwhile(curr!=null){// Store nextnext=curr.Next;// Reverse current node's next pointercurr.Next=prev;// Move pointers one position aheadprev=curr;curr=next;}// Return the head of reversed linked listreturnprev;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(" "+node.Data);node=node.Next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);Console.Write("Given Linked list:");PrintList(head);head=ReverseList(head);Console.Write("Reversed Linked List:");PrintList(head);}}
JavaScript
// Iterative JavaScript program to reverse a linked listclassNode{constructor(newData){this.data=newData;this.next=null;}}// Given the head of a list, reverse the list and return the// head of reversed listfunctionreverseList(head){// Initialize three pointers: curr, prev and nextletcurr=head;letprev=null;letnext;// Traverse all the nodes of Linked Listwhile(curr!==null){// Store nextnext=curr.next;// Reverse current node's next pointercurr.next=prev;// Move pointers one position aheadprev=curr;curr=next;}// Return the head of reversed linked listreturnprev;}functionprintList(node){while(node!==null){console.log(" "+node.data);node=node.next;}console.log();}// Driver Code// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);console.log("Given Linked list:");printList(head);head=reverseList(head);console.log("Reversed Linked List:");printList(head);
[Alternate Approach - 1] Using Recursion - O(n) Time and O(n) Space
The idea is to reach the last node of the linked list using recursion then start reversing the linked list from the last node.
Follow the steps below to solve the problem:
Divide the list in two parts - first node and rest of the linked list.
Call reverse for the rest of the linked list.
Link the rest linked list to first.
Fix head pointer to NULL.
C++
// Recursive C++ program to reverse a linked list#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Given the head of a list, reverse the list// and return the head of reversed listNode*reverseList(Node*head){if(head==NULL||head->next==NULL)returnhead;// reverse the rest of linked list and put// the first element at the endNode*rest=reverseList(head->next);// Make the current head as last node of// remaining linked listhead->next->next=head;// Update next of current head to NULLhead->next=NULL;// Return the reversed linked listreturnrest;}voidprintList(Node*node){while(node!=nullptr){cout<<" "<<node->data;node=node->next;}}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);cout<<"Given Linked List:";printList(head);head=reverseList(head);cout<<"\nReversed Linked List:";printList(head);return0;}
C
// Recursive C program to reverse a linked list#include<stdio.h>structNode{intdata;structNode*next;};// Given the head of a list, reverse the list and // return the head of reversed liststructNode*reverseList(structNode*head){if(head==NULL||head->next==NULL)returnhead;// reverse the rest of linked list and put // the first element at the endstructNode*rest=reverseList(head->next);// Make the current head as last node of // remaining linked listhead->next->next=head;// Update next of current head to NULLhead->next=NULL;// Return the reversed linked listreturnrest;}// This function prints the contents// of the linked list starting from the headvoidprintList(structNode*node){while(node!=NULL){printf(" %d",node->data);node=node->next;}printf("\n");}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);printf("Given Linked List:");printList(head);head=reverseList(head);printf("Reversed Linked List:");printList(head);return0;}
Java
// Recursive Java program to reverse a linked listclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{// Given the head of a list, reverse the list // and return the head of reversed liststaticNodereverseList(Nodehead){// If we have reached last node or linked// list is empty, return head of linked listif(head==null||head.next==null)returnhead;// reverse the rest of linked list and put // the first element at the endNoderest=reverseList(head.next);// Make the current head as last node of // remaining linked listhead.next.next=head;// Update next of current head to NULLhead.next=null;// Return the reversed linked listreturnrest;}// This function prints the contents// of the linked list starting from the headstaticvoidprintList(Nodenode){while(node!=null){System.out.print(" "+node.data);node=node.next;}}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);System.out.print("Given Linked List:");printList(head);head=reverseList(head);System.out.print("\nReversed Linked List:");printList(head);}}
Python
# Recursive Python program to reverse a linked listclassNode:def__init__(self,newData):self.data=newDataself.next=None# Given the head of a list, reverse the list and # return the head of reversed listdefreverseList(head):ifheadisNoneorhead.nextisNone:returnhead# reverse the rest of linked list and put the # first element at the endrest=reverseList(head.next)# Make the current head as last node of # remaining linked listhead.next.next=head# Update next of current head to NULLhead.next=None# Return the reversed linked listreturnrestdefprintList(node):whilenodeisnotNone:print(f" {node.data}",end='')node=node.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)print("Given Linked List:",end='')printList(head)head=reverseList(head)print("\nReversed Linked List:",end='')printList(head)
C#
// Recursive C# program to reverse a linked listusingSystem;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}classGfG{// Given the head of a list, reverse the list // and return the head of reversed liststaticNodeReverseList(Nodehead){if(head==null||head.Next==null)returnhead;// reverse the rest of linked list and // put the first element at the endNoderest=ReverseList(head.Next);// Make the current head as last node // of remaining linked listhead.Next.Next=head;// Update next of current head to NULLhead.Next=null;// Return the reversed linked listreturnrest;}// This function prints the contents// of the linked list starting from the headstaticvoidPrintList(Nodenode){while(node!=null){Console.Write(" "+node.Data);node=node.Next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);Console.Write("Given Linked List:");PrintList(head);head=ReverseList(head);Console.Write("\nReversed Linked List:");PrintList(head);}}
JavaScript
// Recursive javascript program to reverse a linked listclassNode{constructor(new_data){this.data=new_data;this.next=null;}}// Given the head of a list, reverse the list // and return the head of reversed listfunctionreverseList(head){if(head===null||head.next===null)returnhead;// reverse the rest of linked list and // put the first element at the endletrest=reverseList(head.next);// Make the current head as last node of // remaining linked listhead.next.next=head;// Update next of current head to NULLhead.next=null;// Return the reversed linked listreturnrest;}functionprintList(node){while(node!==null){console.log(` ${node.data}`);node=node.next;}console.log();}// Driver Code// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);console.log("Given Linked List:");printList(head);head=reverseList(head);console.log("\nReversed Linked List:");printList(head);
[Alternate Approach - 2] Using Stack - O(n) Time and O(n) Space
The idea is to traverse the linked list and push all nodes except the last node into the stack. Make the last node as the new head of the reversed linked list. Now, start popping the element and append each node to the reversed Linked List. Finally, return the head of the reversed linked list.
Follow the steps below to solve the problem:
Push all the nodes(values and address) except the last node in the stack.
Once the nodes are pushed, update the Head pointer to the last node.
Start popping the nodes and push them at the end of the linked list in the same order until the stack is empty.
Update the next pointer of last node in the stack by NULL.
C++
// C++ program to reverse linked list using Stack#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to reverse the linked listNode*reverseList(Node*head){// Create a stack to store the nodesstack<Node*>s;Node*temp=head;// Push all nodes except the last node into stackwhile(temp->next!=NULL){s.push(temp);temp=temp->next;}// Make the last node as new head of the linked listhead=temp;// Pop all the nodes and append to the linked listwhile(!s.empty()){// append the top value of stack in listtemp->next=s.top();// Pop the value from stacks.pop();// move to the next node in the listtemp=temp->next;}// Update the next pointer of last node of stack to NULLtemp->next=NULL;returnhead;}voidprintList(Node*node){while(node!=nullptr){cout<<" "<<node->data;node=node->next;}}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);cout<<"Given Linked List:";printList(head);head=reverseList(head);cout<<"\nReversed Linked List:";printList(head);return0;}
C
// C program to reverse linked list using Stack#include<stdio.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}// Function to reverse the linked liststructNode*reverseList(structNode*head){// Create a stack to store the nodesstructNode*stack[100000];inttop=-1;structNode*temp=head;// Push all nodes except the last node into stackwhile(temp!=NULL){stack[++top]=temp;temp=temp->next;}// Make the last node as new head of the linked listif(top>=0){head=stack[top];temp=head;// Pop all the nodes and append to the linked listwhile(top>0){// append the top value of stack in list and // pop the top value by decrementing top by 1temp->next=stack[--top];// move to the next node in the listtemp=temp->next;}// Update the next pointer of last node of stack to NULLtemp->next=NULL;}returnhead;}voidprintList(structNode*node){while(node!=NULL){printf(" %d",node->data);node=node->next;}printf("\n");}intmain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);printf("Given Linked List:");printList(head);head=reverseList(head);printf("\nReversed Linked List:");printList(head);return0;}
Java
// Java program to reverse linked list using Stackimportjava.util.Stack;classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{// Function to reverse the linked liststaticNodereverseList(Nodehead){// Create a stack to store the nodesStack<Node>stack=newStack<>();Nodetemp=head;// Push all nodes except the last node into stackwhile(temp!=null){stack.push(temp);temp=temp.next;}// Make the last node as new head of the linked listif(!stack.isEmpty()){head=stack.pop();temp=head;// Pop all the nodes and append to the linked listwhile(!stack.isEmpty()){// append the top value of stack in listtemp.next=stack.pop();// move to the next node in the listtemp=temp.next;}// Update the next pointer of last node // of stack to NULLtemp.next=null;}returnhead;}// This function prints the contents // of the linked list starting from the headstaticvoidprintList(Nodenode){while(node!=null){System.out.print(" "+node.data);node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);System.out.print("Given Linked List:");printList(head);head=reverseList(head);System.out.print("\nReversed Linked List:");printList(head);}}
Python
# Python program to reverse linked list using StackclassNode:def__init__(self,new_data):self.data=new_dataself.next=NonedefreverseList(head):# Create a stack to store the nodesstack=[]temp=head# Push all nodes except the last node into stackwhiletemp.nextisnotNone:stack.append(temp)temp=temp.next# Make the last node as new head of the linked listhead=temp# Pop all the nodes and append to the linked listwhilestack:# append the top value of stack in listtemp.next=stack.pop()# move to the next node in the listtemp=temp.next# Update the next pointer of last node # of stack to Nonetemp.next=NonereturnheaddefprintList(node):whilenodeisnotNone:print(f" {node.data}",end="")node=node.nextprint()# Create a hard-coded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)print("Given Linked List:",end="")printList(head)head=reverseList(head)print("Reversed Linked List:",end="")printList(head)
C#
// C# program to reverse linked list using stackusingSystem;usingSystem.Collections.Generic;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}classGfG{// Function to reverse the linked liststaticNodeReverseList(Nodehead){// Create a stack to store the nodesStack<Node>stack=newStack<Node>();Nodetemp=head;// Push all nodes except the last node into stackwhile(temp.Next!=null){stack.Push(temp);temp=temp.Next;}// Make the last node as new head of the linked list head=temp;// Pop all the nodes and append to the linked listwhile(stack.Count>0){// append the top value of stack in listtemp.Next=stack.Pop();// move to the next node in the listtemp=temp.Next;}// Update the next pointer of last node of stack to nulltemp.Next=null;returnhead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(" "+node.Data);node=node.Next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);Console.Write("Given Linked List:");PrintList(head);head=ReverseList(head);Console.Write("\nReversed Linked List:");PrintList(head);}}
JavaScript
// JavaScript program to reverse linked list using StackclassNode{constructor(newData){this.data=newData;this.next=null;}}// Function to reverse the linked listfunctionreverseList(head){// Create a stack to store the nodesletstack=[];lettemp=head;// Push all nodes except the last node into stackwhile(temp.next!==null){stack.push(temp);temp=temp.next;}// Make the last node as new head of the Linked Listhead=temp;// Pop all the nodes and append to the linked listwhile(stack.length>0){// append the top value of stack in listtemp.next=stack.pop();// move to the next node in the listtemp=temp.next;}// Update the next pointer of last node of stack to nulltemp.next=null;returnhead;}functionprintList(node){while(node!==null){console.log(" "+node.data);node=node.next;}console.log();}// Create a hard-coded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);console.log("Given Linked List:");printList(head);// Function call to return the reversed listhead=reverseList(head);console.log("\nReversed Linked List:");printList(head);
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.