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
Then move all three pointers (prev, curr and next) forward until the list is fully reversed.
At the end, prev becomes new head
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
Recursion Method- 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.
Divide the list in two parts - first node and rest of the linked list.
Recursively call reverse for the rest of the linked list.
Link the rest linked list to first by making next of next of head to point to itself.
Fix next of head node to NULL to make it last.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*reverseList(Node*head){if(head==nullptr||head->next==nullptr)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=nullptr;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__":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){if(head==null||head.next==null)returnhead;// Reverse the rest of the linked list and// put the first element at the endNoderest=reverseList(head.next);// Make the current head as the last node// of the 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
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 headof 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!=nullptr){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=nullptr;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__":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;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 the stackwhile(temp!=null){stack.Push(temp);temp=temp.next;}// Make the last node as the new head of the linked listif(stack.Count>0){head=stack.Pop();temp=head;// Pop all the nodes and append them 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);