[Approach] Using Iterative Method - O(n) Time and O(1) Space
The idea is to reverse the linked list by changing the direction of links using three pointers: prev, curr, and next. At each step, point the current node to its previous node and then move all three pointers forward until the list is fully reversed.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*reverseList(Node*head){Node*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;}returnprev;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data;if(node->next)cout<<" -> ";node=node->next;}}intmain(){Node*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);head=reverseList(head);printList(head);return0;}
C
#include<stdio.h>structNode{intdata;structNode*next;};structNode*reverseList(structNode*head){structNode*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;}returnprev;}voidprintList(structNode*node){while(node!=NULL){printf("%d",node->data);if(node->next)printf(" -> ");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(){structNode*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);head=reverseList(head);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNodereverseList(Nodehead){Nodecurr=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;}returnprev;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null)System.out.print(" -> ");node=node.next;}}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);}}
Python
classNode:def__init__(self,newData):self.data=newDataself.next=NonedefreverseList(head):curr=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=nextNodereturnprevdefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head=reverseList(head)printList(head)
C#
usingSystem;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}classGfG{staticNodeReverseList(Nodehead){Nodecurr=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;}returnprev;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(""+node.Data);if(node.Next!=null)Console.Write(" -> ");node=node.Next;}Console.WriteLine();}staticvoidMain(){Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);head=ReverseList(head);printList(head);}}
JavaScript
classNode{constructor(newData){this.data=newData;this.next=null;}}functionreverseList(head){letcurr=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;}returnprev;}functionprintList(node){letresult=[];while(node!==null){result.push(node.data);node=node.next;}console.log(result.join(" -> "));}// Driver Codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);
Output
5 -> 4 -> 3 -> 2 -> 1
[Alternate Approach 1] Using Recursion Method- O(n) Time and O(n) Space
The idea is to use recursion to reach the last node of the list, which becomes the new head after reversal. As the recursion starts returning, each node makes its next node point back to itself, effectively reversing the links one by one until the entire list is reversed.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*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;returnrest;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data;if(node->next)cout<<" -> ";node=node->next;}}intmain(){Node*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);head=reverseList(head);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*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;returnrest;}voidprintList(structNode*node){while(node!=NULL){printf("%d",node->data);if(node->next)printf(" -> ");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(){structNode*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);head=reverseList(head);printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNodereverseList(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;returnrest;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null)System.out.print(" -> ");node=node.next;}}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);}}
Python
classNode:def__init__(self,newData):self.data=newDataself.next=NonedefreverseList(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=NonereturnrestdefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",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)head=reverseList(head)printList(head)
C#
usingSystem;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}classGfG{staticNodeReverseList(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;returnrest;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(""+node.Data);if(node.Next!=null)Console.Write(" -> ");node=node.Next;}Console.WriteLine();}staticvoidMain(){Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);head=ReverseList(head);PrintList(head);}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionreverseList(head){if(head===null||head.next===null)returnhead;// reverse the rest of linked listletrest=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;returnrest;}functionprintList(node){letresult=[];while(node!==null){result.push(node.data);node=node.next;}console.log(result.join(" -> "));}// Driver codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);
Output
5 -> 4 -> 3 -> 2 -> 1
[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 headof 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.
C++
#include<iostream>#include<stack>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*reverseList(Node*head){stack<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();s.pop();temp=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;if(node->next)cout<<" -> ";node=node->next;}}intmain(){Node*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);head=reverseList(head);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}structNode*reverseList(structNode*head){structNode*stack[100000];inttop=-1;structNode*temp=head;// push all nodes 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 listtemp->next=stack[--top];temp=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);if(node->next)printf(" -> ");node=node->next;}printf("\n");}intmain(){structNode*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);head=reverseList(head);printList(head);return0;}
Java
importjava.util.Stack;classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNodereverseList(Nodehead){Stack<Node>stack=newStack<>();Nodetemp=head;// push all nodes 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();temp=temp.next;}// update the next pointer of last node to nulltemp.next=null;}returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data);if(node.next!=null)System.out.print(" -> ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=NonedefreverseList(head):stack=[]temp=head# push all nodes except the last node into stackwhiletemp.nextisnotNone:stack.append(temp)temp=temp.nexthead=temp# pop all the nodes and append to the linked listwhilestack:# append the top value of stack in listtemp.next=stack.pop()temp=temp.nexttemp.next=NonereturnheaddefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",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)head=reverseList(head)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintData;publicNodeNext;publicNode(intnewData){Data=newData;Next=null;}}classGfG{staticNodeReverseList(Nodehead){Stack<Node>stack=newStack<Node>();Nodetemp=head;// push all nodes into stackwhile(temp!=null){stack.Push(temp);temp=temp.Next;}// make the last node as new head of the linked listif(stack.Count>0){head=stack.Pop();temp=head;// pop all the nodes and append to the linked listwhile(stack.Count>0){temp.Next=stack.Pop();temp=temp.Next;}temp.Next=null;}returnhead;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(""+node.Data);if(node.Next!=null)Console.Write(" -> ");node=node.Next;}Console.WriteLine();}staticvoidMain(){Nodehead=newNode(1);head.Next=newNode(2);head.Next.Next=newNode(3);head.Next.Next.Next=newNode(4);head.Next.Next.Next.Next=newNode(5);head=ReverseList(head);printList(head);}}
JavaScript
classNode{constructor(newData){this.data=newData;this.next=null;}}functionreverseList(head){letstack=[];lettemp=head;// push all nodes into stackwhile(temp!==null){stack.push(temp);temp=temp.next;}// make the last node as new head of the linked listif(stack.length>0){head=stack.pop();temp=head;// pop all the nodes and append to the linked listwhile(stack.length>0){temp.next=stack.pop();temp=temp.next;}temp.next=null;}returnhead;}functionprintList(node){letresult=[];while(node!==null){result.push(node.data);node=node.next;}console.log(result.join(" -> "));}// driver codelethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head=reverseList(head);printList(head);