Reverse a linked list
- Difficulty Level : Medium
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing the links between nodes.
Examples:
Input: Head of following linked list
1->2->3->4->NULL
Output: Linked list should be changed to,
4->3->2->1->NULLInput: Head of following linked list
1->2->3->4->5->NULL
Output: Linked list should be changed to,
5->4->3->2->1->NULLInput: NULL
Output: NULLInput: 1->NULL
Output: 1->NULL
Iterative Method
- Initialize three pointers prev as NULL, curr as head and next as NULL.
- Iterate through the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
// Now change next of current
// This is where actual reversing happens
curr->next = prev
// Move prev and curr one step forward
prev = curr
curr = next
Below is the implementation of the above approach:
C++
// Iterative C++ program to reverse a linked list#include <iostream>usingnamespacestd;/* Link list node */structNode {intdata;structNode* next;Node(intdata){this->data = data;next = NULL;}};structLinkedList {Node* head;LinkedList() { head = NULL; }/* Function to reverse the linked list */voidreverse(){// Initialize current, previous and next pointersNode* current = head;Node *prev = NULL, *next = NULL;while(current != NULL) {// Store nextnext = current->next;// Reverse current node's pointercurrent->next = prev;// Move pointers one position ahead.prev = current;current = next;}head = prev;}/* Function to print linked list */voidprint(){structNode* temp = head;while(temp != NULL) {cout << temp->data <<" ";temp = temp->next;}}voidpush(intdata){Node* temp =newNode(data);temp->next = head;head = temp;}};/* Driver code*/intmain(){/* Start with the empty list */LinkedList ll;ll.push(20);ll.push(4);ll.push(15);ll.push(85);cout <<"Given linked list\n";ll.print();ll.reverse();cout <<"\nReversed Linked list \n";ll.print();return0;}C
// Iterative C program to reverse a linked list#include <stdio.h>#include <stdlib.h>/* Link list node */structNode {intdata;structNode* next;};/* Function to reverse the linked list */staticvoidreverse(structNode** head_ref){structNode* prev = NULL;structNode* current = *head_ref;structNode* next = NULL;while(current != NULL) {// Store nextnext = current->next;// Reverse current node's pointercurrent->next = prev;// Move pointers one position ahead.prev = current;current = next;}*head_ref = prev;}/* Function to push a node */voidpush(structNode** head_ref,intnew_data){structNode* new_node= (structNode*)malloc(sizeof(structNode));new_node->data = new_data;new_node->next = (*head_ref);(*head_ref) = new_node;}/* Function to print linked list */voidprintList(structNode* head){structNode* temp = head;while(temp != NULL) {printf("%d ", temp->data);temp = temp->next;}}/* Driver code*/intmain(){/* Start with the empty list */structNode* head = NULL;push(&head;, 20);push(&head;, 4);push(&head;, 15);push(&head;, 85);printf("Given linked list\n");printList(head);reverse(&head;);printf("\nReversed Linked list \n");printList(head);getchar();}Java
// Java program for reversing the linked listclassLinkedList {staticNode head;staticclassNode {intdata;Node next;Node(intd){data = d;next =null;}}/* Function to reverse the linked list */Node reverse(Node node){Node prev =null;Node current = node;Node next =null;while(current !=null) {next = current.next;current.next = prev;prev = current;current = next;}node = prev;returnnode;}// prints content of double linked listvoidprintList(Node node){while(node !=null) {System.out.print(node.data +" ");node = node.next;}}// Driver Codepublicstaticvoidmain(String[] args){LinkedList list =newLinkedList();list.head =newNode(85);list.head.next =newNode(15);list.head.next.next =newNode(4);list.head.next.next.next =newNode(20);System.out.println("Given Linked list");list.printList(head);head = list.reverse(head);System.out.println("");System.out.println("Reversed linked list ");list.printList(head);}}// This code has been contributed by Mayank JaiswalPython
# Python program to reverse a linked list# Time Complexity : O(n)# Space Complexity : O(1)# Node classclassNode:# Constructor to initialize the node objectdef__init__(self, data):self.data=dataself.next=NoneclassLinkedList:# Function to initialize headdef__init__(self):self.head=None# Function to reverse the linked listdefreverse(self):prev=Nonecurrent=self.headwhile(currentisnotNone):next=current.nextcurrent.next=prevprev=currentcurrent=nextself.head=prev# Function to insert a new node at the beginningdefpush(self, new_data):new_node=Node(new_data)new_node.next=self.headself.head=new_node# Utility function to print the linked LinkedListdefprintList(self):temp=self.headwhile(temp):temp.data,temp=temp.next# Driver codellist=LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(85)"Given Linked List"llist.printList()llist.reverse()"\nReversed Linked List"llist.printList()# This code is contributed by Nikhil Kumar Singh(nickzuck_007)C#
// C# program for reversing the linked listusingSystem;classGFG {// Driver CodestaticvoidMain(string[] args){LinkedList list =newLinkedList();list.AddNode(newLinkedList.Node(85));list.AddNode(newLinkedList.Node(15));list.AddNode(newLinkedList.Node(4));list.AddNode(newLinkedList.Node(20));// List before reversalConsole.WriteLine("Given linked list:");list.PrintList();// Reverse the listlist.ReverseList();// List after reversalConsole.WriteLine("Reversed linked list:");list.PrintList();}}classLinkedList {Node head;publicclassNode {publicintdata;publicNode next;publicNode(intd){data = d;next =null;}}// function to add a new node at// the end of the listpublicvoidAddNode(Node node){if(head ==null)head = node;else{Node temp = head;while(temp.next !=null) {temp = temp.next;}temp.next = node;}}// function to reverse the listpublicvoidReverseList(){Node prev =null, current = head, next =null;while(current !=null) {next = current.next;current.next = prev;prev = current;current = next;}head = prev;}// function to print the list datapublicvoidPrintList(){Node current = head;while(current !=null) {Console.Write(current.data +" ");current = current.next;}Console.WriteLine();}}// This code is contributed by Mayank SharmaJavascript
<script>// JavaScript program for reversing the linked listvarhead;class Node {constructor(val) {this.data = val;this.next =null;}}/* Function to reverse the linked list */functionreverse(node) {varprev =null;varcurrent = node;varnext =null;while(current !=null) {next = current.next;current.next = prev;prev = current;current = next;}node = prev;returnnode;}// prints content of double linked listfunctionprintList(node) {while(node !=null) {document.write(node.data +" ");node = node.next;}}// Driver Codehead =newNode(85);head.next =newNode(15);head.next.next =newNode(4);head.next.next.next =newNode(20);document.write("Given Linked list<br/>");printList(head);head = reverse(head);document.write("<br/>");document.write("Reversed linked list<br/> ");printList(head);// This code is contributed by todaysgaurav</script>Output:
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85Time Complexity: O(n)
Auxiliary Space: O(1)Recursive Method:
1) Divide the list in two parts - first node and rest of the linked list. 2) Call reverse for the rest of the linked list. 3) Link rest to first. 4) Fix head pointer
C++
// Recursive C++ program to reverse// a linked list#include <iostream>usingnamespacestd;/* Link list node */structNode {intdata;structNode* next;Node(intdata){this->data = data;next = NULL;}};structLinkedList {Node* head;LinkedList(){head = NULL;}Node* reverse(Node* head){if(head == NULL || head->next == NULL)returnhead;/* reverse the rest list and putthe first element at the end */Node* rest = reverse(head->next);head->next->next = head;/* tricky step -- see the diagram */head->next = NULL;/* fix the head pointer */returnrest;}/* Function to print linked list */voidprint(){structNode* temp = head;while(temp != NULL) {cout << temp->data <<" ";temp = temp->next;}}voidpush(intdata){Node* temp =newNode(data);temp->next = head;head = temp;}};/* Driver program to test above function*/intmain(){/* Start with the empty list */LinkedList ll;ll.push(20);ll.push(4);ll.push(15);ll.push(85);cout <<"Given linked list\n";ll.print();ll.head = ll.reverse(ll.head);cout <<"\nReversed Linked list \n";ll.print();return0;}Java
// Recursive Java program to reverse// a linked listclassrecursion {staticNode head;// head of liststaticclassNode {intdata;Node next;Node(intd){data = d;next =null;}}staticNode reverse(Node head){if(head ==null|| head.next ==null)returnhead;/* reverse the rest list and putthe first element at the end */Node rest = reverse(head.next);head.next.next = head;/* tricky step -- see the diagram */head.next =null;/* fix the head pointer */returnrest;}/* Function to print linked list */staticvoidprint(){Node temp = head;while(temp !=null) {System.out.print(temp.data +" ");temp = temp.next;}System.out.println();}staticvoidpush(intdata){Node temp =newNode(data);temp.next = head;head = temp;}/* Driver program to test above function*/publicstaticvoidmain(String args[]){/* Start with the empty list */push(20);push(4);push(15);push(85);System.out.println("Given linked list");print();head = reverse(head);System.out.println("Reversed Linked list");print();}}// This code is contributed by Prakhar AgarwalPython3
"""Python3 program to reverse linked listusing recursive method"""# Linked List NodeclassNode:def__init__(self, data):self.data=dataself.next=None# Create and Handle list operationsclassLinkedList:def__init__(self):self.head=None# Head of list# Method to reverse the listdefreverse(self, head):# If head is empty or has reached the list endifheadisNoneorhead.nextisNone:returnhead# Reverse the rest listrest=self.reverse(head.next)# Put first element at the endhead.next.next=headhead.next=None# Fix the header pointerreturnrest# Returns the linked list in display formatdef__str__(self):linkedListStr=""temp=self.headwhiletemp:linkedListStr=(linkedListStr+str(temp.data)+" ")temp=temp.nextreturnlinkedListStr# Pushes new data to the head of the listdefpush(self, data):temp=Node(data)temp.next=self.headself.head=temp# Driver codelinkedList=LinkedList()linkedList.push(20)linkedList.push(4)linkedList.push(15)linkedList.push(85)("Given linked list")(linkedList)linkedList.head=linkedList.reverse(linkedList.head)("Reversed linked list")(linkedList)# This code is contributed by Debidutta RathC#
// Recursive C# program to// reverse a linked listusingSystem;classrecursion{// Head of liststaticNode head;publicclassNode{publicintdata;publicNode next;publicNode(intd){data = d;next =null;}}staticNode reverse(Node head){if(head ==null||head.next ==null)returnhead;// Reverse the rest list and put// the first element at the endNode rest = reverse(head.next);head.next.next = head;// Tricky step --// see the diagramhead.next =null;// Fix the head pointerreturnrest;}// Function to print// linked liststaticvoidprint(){Node temp = head;while(temp !=null){Console.Write(temp.data +" ");temp = temp.next;}Console.WriteLine();}staticvoidpush(intdata){Node temp =newNode(data);temp.next = head;head = temp;}// Driver codepublicstaticvoidMain(String []args){// Start with the// empty listpush(20);push(4);push(15);push(85);Console.WriteLine("Given linked list");print();head = reverse(head);Console.WriteLine("Reversed Linked list");print();}}// This code is contributed by gauravrajput1Javascript
<script>// Recursive javascript program to reverse// a linked listvarhead;// head of listclass Node {constructor(val) {this.data = val;this.next =null;}}functionreverse(head) {if(head ==null|| head.next ==null)returnhead;/** reverse the rest list and put the first element at the end*/varrest = reverse(head.next);head.next.next = head;/* tricky step -- see the diagram */head.next =null;/* fix the head pointer */returnrest;}/* Function to print linked list */functionprint() {vartemp = head;while(temp !=null) {document.write(temp.data +" ");temp = temp.next;}document.write();}functionpush(data) {vartemp =newNode(data);temp.next = head;head = temp;}/* Driver program to test above function *//* Start with the empty list */push(20);push(4);push(15);push(85);document.write("Given linked list<br/>");print();head = reverse(head);document.write("<br/>Reversed Linked list<br/>");print();// This code is contributed by Rajput-Ji</script>Output:
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85Time Complexity: O(n)
Auxiliary Space: O(n)A Simpler and Tail Recursive Method
Below is the implementation of this method.
C++
// A simple and tail recursive C++ program to reverse// a linked list#include <bits/stdc++.h>usingnamespacestd;structNode {intdata;structNode* next;};voidreverseUtil(Node* curr, Node* prev, Node** head);// This function mainly calls reverseUtil()// with prev as NULLvoidreverse(Node** head){if(!head)return;reverseUtil(*head, NULL, head);}// A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.voidreverseUtil(Node* curr, Node* prev, Node** head){/* If last node mark it head*/if(!curr->next) {*head = curr;/* Update next to prev node */curr->next = prev;return;}/* Save curr->next node for recursive call */Node* next = curr->next;/* and update next ..*/curr->next = prev;reverseUtil(next, curr, head);}// A utility function to create a new nodeNode* newNode(intkey){Node* temp =newNode;temp->data = key;temp->next = NULL;returntemp;}// A utility function to print a linked listvoidprintlist(Node* head){while(head != NULL) {cout << head->data <<" ";head = head->next;}cout << endl;}// Driver codeintmain(){Node* head1 = newNode(1);head1->next = newNode(2);head1->next->next = newNode(3);head1->next->next->next = newNode(4);head1->next->next->next->next = newNode(5);head1->next->next->next->next->next = newNode(6);head1->next->next->next->next->next->next = newNode(7);head1->next->next->next->next->next->next->next = newNode(8);cout <<"Given linked list\n";printlist(head1);reverse(&head1;);cout <<"\nReversed linked list\n";printlist(head1);return0;}// This code is contributed by Aditya Kumar (adityakumar129)C
// A simple and tail recursive C program to reverse a linked list#include <stdio.h>#include <stdlib.h>typedefstructNode {intdata;structNode* next;}Node;voidreverseUtil(Node* curr, Node* prev, Node** head);// This function mainly calls reverseUtil()// with prev as NULLvoidreverse(Node** head){if(!head)return;reverseUtil(*head, NULL, head);}// A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.voidreverseUtil(Node* curr, Node* prev, Node** head){/* If last node mark it head*/if(!curr->next) {*head = curr;/* Update next to prev node */curr->next = prev;return;}/* Save curr->next node for recursive call */Node* next = curr->next;/* and update next ..*/curr->next = prev;reverseUtil(next, curr, head);}// A utility function to create a new nodeNode* newNode(intkey){Node* temp = (Node *)malloc(sizeof(Node));temp->data = key;temp->next = NULL;returntemp;}// A utility function to print a linked listvoidprintlist(Node* head){while(head != NULL) {printf("%d ",head->data);head = head->next;}printf("\n");}// Driver codeintmain(){Node* head1 = newNode(1);head1->next = newNode(2);head1->next->next = newNode(3);head1->next->next->next = newNode(4);head1->next->next->next->next = newNode(5);head1->next->next->next->next->next = newNode(6);head1->next->next->next->next->next->next = newNode(7);head1->next->next->next->next->next->next->next = newNode(8);printf("Given linked list\n");printlist(head1);reverse(&head1;);printf("\nReversed linked list\n");printlist(head1);return0;}// This code is contributed by Aditya Kumar (adityakumar129)Java
// Java program for reversing the Linked listclassLinkedList {staticNode head;staticclassNode {intdata;Node next;Node(intd){data = d;next =null;}}// A simple and tail recursive function to reverse// a linked list. prev is passed as NULL initially.Node reverseUtil(Node curr, Node prev){/*If head is initially null OR list is empty*/if(head ==null)returnhead;/* If last node mark it head*/if(curr.next ==null) {head = curr;/* Update next to prev node */curr.next = prev;returnhead;}/* Save curr->next node for recursive call */Node next1 = curr.next;/* and update next ..*/curr.next = prev;reverseUtil(next1, curr);returnhead;}// prints content of double linked listvoidprintList(Node node){while(node !=null) {System.out.print(node.data +" ");node = node.next;}}// Driver Codepublicstaticvoidmain(String[] args){LinkedList list =newLinkedList();list.head =newNode(1);list.head.next =newNode(2);list.head.next.next =newNode(3);list.head.next.next.next =newNode(4);list.head.next.next.next.next =newNode(5);list.head.next.next.next.next.next =newNode(6);list.head.next.next.next.next.next.next =newNode(7);list.head.next.next.next.next.next.next.next =newNode(8);System.out.println("Original Linked list ");list.printList(head);Node res = list.reverseUtil(head,null);System.out.println("");System.out.println("");System.out.println("Reversed linked list ");list.printList(res);}}// This code is contributed by Aditya Kumar (adityakumar129)Python
# Simple and tail recursive Python program to# reverse a linked list# Node classclassNode:# Constructor to initialize the node objectdef__init__(self, data):self.data=dataself.next=NoneclassLinkedList:# Function to initialize headdef__init__(self):self.head=NonedefreverseUtil(self, curr, prev):# If last node mark it headifcurr.nextisNone:self.head=curr# Update next to prev nodecurr.next=prevreturn# Save curr.next node for recursive callnext=curr.next# And update nextcurr.next=prevself.reverseUtil(next, curr)# This function mainly calls reverseUtil()# with previous as Nonedefreverse(self):ifself.headisNone:returnself.reverseUtil(self.head,None)# Function to insert a new node at the beginningdefpush(self, new_data):new_node=Node(new_data)new_node.next=self.headself.head=new_node# Utility function to print the linked LinkedListdefprintList(self):temp=self.headwhile(temp):temp.data,temp=temp.next# Driver codellist=LinkedList()llist.push(8)llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1)"Given linked list"llist.printList()llist.reverse()"\nReverse linked list"llist.printList()# This code is contributed by Nikhil Kumar Singh(nickzuck_007)C#
// C# program for reversing the Linked listusingSystem;publicclassLinkedList {Node head;publicclassNode {publicintdata;publicNode next;publicNode(intd){data = d;next =null;}}// A simple and tail-recursive function to reverse// a linked list. prev is passed as NULL initially.Node reverseUtil(Node curr, Node prev){/* If last node mark it head*/if(curr.next ==null) {head = curr;/* Update next to prev node */curr.next = prev;returnhead;}/* Save curr->next node for recursive call */Node next1 = curr.next;/* and update next ..*/curr.next = prev;reverseUtil(next1, curr);returnhead;}// prints content of double linked listvoidprintList(Node node){while(node !=null) {Console.Write(node.data +" ");node = node.next;}}// Driver codepublicstaticvoidMain(String[] args){LinkedList list =newLinkedList();list.head =newNode(1);list.head.next =newNode(2);list.head.next.next =newNode(3);list.head.next.next.next =newNode(4);list.head.next.next.next.next =newNode(5);list.head.next.next.next.next.next =newNode(6);list.head.next.next.next.next.next.next=newNode(7);list.head.next.next.next.next.next.next.next=newNode(8);Console.WriteLine("Original Linked list ");list.printList(list.head);Node res = list.reverseUtil(list.head,null);Console.WriteLine("");Console.WriteLine("");Console.WriteLine("Reversed linked list ");list.printList(res);}}// This code contributed by Rajput-JiJavascript
<script>// javascript program for reversing the Linked listvarhead;class Node {constructor(d) {this.data = d;this.next =null;}}// A simple and tail recursive function to reverse// a linked list. prev is passed as NULL initially.functionreverseUtil(curr, prev){/* If head is initially null OR list is empty */if(head ==null)returnhead;/* If last node mark it head */if(curr.next ==null) {head = curr;/* Update next to prev node */curr.next = prev;returnhead;}/* Save curr->next node for recursive call */varnext1 = curr.next;/* and update next .. */curr.next = prev;reverseUtil(next1, curr);returnhead;}// prints content of var linked listfunctionprintList(node) {while(node !=null) {document.write(node.data +" ");node = node.next;}}// Driver Codevarhead =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.next.next.next.next.next =newNode(6);head.next.next.next.next.next.next =newNode(7);head.next.next.next.next.next.next.next =newNode(8);document.write("Original Linked list<br/> ");printList(head);varres = reverseUtil(head,null);document.write("<br/>");document.write("<br/>");document.write("Reversed linked list <br/>");printList(res);// This code is contributed by Rajput-Ji</script>
OutputGiven linked list 1 2 3 4 5 6 7 8 Reversed linked list 8 7 6 5 4 3 2 1Time Complexity: O(N)
As we do certain operation for every node of the linked list.
Auxiliary Space: O(1)
As constant extra space is used.
Head Recursive Method:
C++
// Head recursive C++ program to reverse a linked list#include <iostream>usingnamespacestd;// Linked list nodeclassNode {public:intdata;Node* next;// constructor: automatically assigns the value to the// data and next pointer to NULLNode(){};Node(intval): data(val), next(NULL){};};voidreverseUtil(Node* curr, Node* prev, Node** headref){// Base Case - If curr is last nodeif(curr->next == NULL) {// Update head of the linked list*headref = curr;// Update next to prev nodecurr->next = prev;return;}// Recursive Call for next nodereverseUtil(curr->next, curr, headref);// Update next to prev nodecurr->next = prev;}voidreverse(Node** headref){// If linked list is empty or contains single nodeif(*headref == NULL || (*headref)->next == NULL)return;// Call reverseUtil() with prev as NULLreverseUtil(*headref, NULL, headref);}// Function to insert a node at the end of linked listvoidpush(Node** headref,intx){Node* newptr =newNode(x);if(*headref == NULL) {*headref = newptr;}else{Node* temp = *headref;while(temp->next != NULL) {temp = temp->next;}temp->next = newptr;}}// Functio to print the linked listvoidprint(Node* headref){while(headref != NULL) {cout << headref->data <<" ";headref = headref->next;}cout <<"\n";}intmain(){Node* head = NULL;// head->1->2->3->4->5->6->NULLpush(&head;, 1);push(&head;, 2);push(&head;, 3);push(&head;, 4);push(&head;, 5);push(&head;, 6);cout <<"Given Linked List\n";print(head);reverse(&head;);cout <<"Reversed Linked List\n";print(head);return0;}//This code is contributed by Anisha WaghOutput:
Given Linked List 1 2 3 4 5 6 Reversed Linked List 6 5 4 3 2 1Time Complexity : O(N)
Using Stack:
Algorithm –
- Store the nodes(values and address) in the stack until all the values are entered.
- Once all entries are done, Update the Head pointer to the last location(i.e the last value).
- Start popping the nodes(value and address) and store them in the same order until the stack is empty.
- Update the next pointer of last Node in the stack by NULL.
Below is the implementation of the above approach:
C++
// C++ program for above approach#include <bits/stdc++.h>#include <iostream>usingnamespacestd;// Create a class Node to enter values and address in the listclassNode {public:intdata;Node* next;};// Function to reverse the linked listvoidreverseLL(Node** head){// Create a stack "s" of Node typestack<Node*> s;Node* temp = *head;while(temp->next != NULL) {// Push all the nodes in to stacks.push(temp);temp = temp->next;}*head = temp;while(!s.empty()) {// Store the top value of stack in listtemp->next = s.top();// Pop the value from stacks.pop();// update the next pointer in the in the listtemp = temp->next;}temp->next = NULL;}// Function to Display the elements in Listvoidprintlist(Node* temp){while(temp != NULL) {cout << temp->data <<" ";temp = temp->next;}}// Program to insert back of the linked listvoidinsert_back(Node** head,intvalue){// we have used insertion at back method to enter values// in the list.(eg: head->1->2->3->4->Null)Node* temp =newNode();temp->data = value;temp->next = NULL;// If *head equals to NULLif(*head == NULL) {*head = temp;return;}else{Node* last_node = *head;while(last_node->next != NULL)last_node = last_node->next;last_node->next = temp;return;}}// Driver Codeintmain(){Node* head = NULL;insert_back(&head;, 1);insert_back(&head;, 2);insert_back(&head;, 3);insert_back(&head;, 4);cout <<"Given linked list\n";printlist(head);reverseLL(&head;);cout <<"\nReversed linked list\n";printlist(head);return0;}// This code is contributed by Aditya Kumar (adityakumar129)Java
// Java program for above approachimportjava.util.*;classGFG {// Create a class Node to enter values and address in the liststaticclassNode {intdata;Node next;};staticNode head =null;// Function to reverse the linked liststaticvoidreverseLL(){// Create a stack "s" of Node typeStack<Node> s =newStack<>();Node temp = head;while(temp.next !=null) {// Push all the nodes in to stacks.add(temp);temp = temp.next;}head = temp;while(!s.isEmpty()) {// Store the top value of stack in listtemp.next = s.peek();// Pop the value from stacks.pop();// update the next pointer in the in the listtemp = temp.next;}temp.next =null;}// Function to Display the elements in Liststaticvoidprintlist(Node temp){while(temp !=null) {System.out.print(temp.data +" ");temp = temp.next;}}// Program to insert back of the linked liststaticvoidinsert_back(intvalue){// we have used insertion at back method to enter// values in the list.(eg: head.1.2.3.4.Null)Node temp =newNode();temp.data = value;temp.next =null;// If *head equals to nullif(head ==null) {head = temp;return;}else{Node last_node = head;while(last_node.next !=null)last_node = last_node.next;last_node.next = temp;return;}}// Driver Codepublicstaticvoidmain(String[] args){insert_back(1);insert_back(2);insert_back(3);insert_back(4);System.out.print("Given linked list\n");printlist(head);reverseLL();System.out.print("\nReversed linked list\n");printlist(head);}}// This code is contributed by Aditya Kumar (adityakumar129)C#
// C# program for above approachusingSystem;usingSystem.Collections.Generic;classGFG{// Create a class Node to enter// values and address in the listpublicclassNode{publicintdata;publicNode next;};staticNode head =null;// Function to reverse the// linked liststaticvoidreverseLL(){// Create a stack "s"// of Node typeStack<Node> s =newStack<Node>();Node temp = head;while(temp.next !=null){// Push all the nodes// in to stacks.Push(temp);temp = temp.next;}head = temp;while(s.Count != 0){// Store the top value of// stack in listtemp.next = s.Peek();// Pop the value from stacks.Pop();// Update the next pointer in the// in the listtemp = temp.next;}temp.next =null;}// Function to Display// the elements in Liststaticvoidprintlist(Node temp){while(temp !=null){Console.Write(temp.data +" ");temp = temp.next;}}// Function to insert back of the// linked liststaticvoidinsert_back(intvalue){// We have used insertion at back method// to enter values in the list.(eg:// head.1.2.3.4.Null)Node temp =newNode();temp.data = value;temp.next =null;// If *head equals to nullif(head ==null){head = temp;return;}else{Node last_node = head;while(last_node.next !=null){last_node = last_node.next;}last_node.next = temp;return;}}// Driver CodepublicstaticvoidMain(String[] args){insert_back(1);insert_back(2);insert_back(3);insert_back(4);Console.Write("Given linked list\n");printlist(head);reverseLL();Console.Write("\nReversed linked list\n");printlist(head);}}// This code is contributed by gauravrajput1Python3
# Python code for the above approach# Definition for singly-linked list.classListNode:def__init__(self, val=0,next=None):self.val=valself.next=nextclassSolution:# Program to reverse the linked list# using stackdefreverseLLUsingStack(self, head):# Initialise the variablesstack, temp=[], headwhiletemp:stack.append(temp)temp=temp.nexthead=temp=stack.pop()# Until stack is not# emptywhilelen(stack) >0:temp.next=stack.pop()temp=temp.nexttemp.next=Nonereturnhead# Driver Codeif__name__=="__main__":head=ListNode(1, ListNode(2, ListNode(3,ListNode(4, ListNode(5)))))obj=Solution()head=obj.reverseLLUsingStack(head)whilehead:(head.val, end=' ')head=head.nextJavascript
<script>// javascript program for above approach// Create a class Node to enter// values and address in the listclass Node{constructor(){this.data = 0;this.next =null;}}varhead =null;// Function to reverse the// linked listfunctionreverseLL(){// Create a stack "s"// of Node typevars = [];vartemp = head;while(temp.next !=null){// Push all the nodes// in to stacks.push(temp);temp = temp.next;}head = temp;while(s.length!=0){// Store the top value of// stack in listtemp.next = s.pop();// update the next pointer in the// in the listtemp = temp.next;}temp.next =null;}// Function to Display// the elements in Listfunctionprintlist(temp){while(temp !=null){document.write(temp.data+" ");temp = temp.next;}}// Program to insert back of the// linked listfunctioninsert_back( value){// we have used insertion at back method// to enter values in the list.(eg:// head.1.2.3.4.Null)vartemp =newNode();temp.data = value;temp.next =null;// If *head equals to nullif(head ==null){head = temp;return;}else{varlast_node = head;while(last_node.next !=null){last_node = last_node.next;}last_node.next = temp;return;}}// Driver Codeinsert_back(1);insert_back(2);insert_back(3);insert_back(4);document.write("Given linked list\n");printlist(head);reverseLL();document.write("<br/>Reversed linked list\n");printlist(head);// This code is contributed by umadevi9616</script>OutputGiven linked list 1 2 3 4 Reversed linked list 4 3 2 1Thanks to Gaurav Ahirwar for suggesting this solution.
Time Complexity: O(N)
As we do certain operation for every node of the linked list.
Auxiliary Space: O(N)
Space is used to store the nodes in the stack.
Using array:
Algorithm :-
1. Create a linked list.
2. Count the number of nodes present in the Linked List
3. Initialize an array with the size of the count.
4. Store the elements of the Linked list in array
5. Print the array from the last index to the first.
C++
#include <bits/stdc++.h>usingnamespacestd;typedefstructnode {intval;structnode* next;} node;node* head = NULL;// Function to return the No of nodes present in the linked listintcount(node* head){node* p = head;intk = 1;while(p != NULL) {p = p->next;k++;}returnk;}node* ll_reverse(node* head)// to reverse the linked list{node* p = head;longinti = count(head), j = 1;longintarr[i];while(i && p != NULL) {arr[j++] = p->val;p = p->next;i--;}j--;while(j)// loop will break as soon as j=0cout << arr[j--] <<" ";returnhead;}// Function to insert node at the end of linked listnode* insert_end(node* head,intdata){node *q = head, *p = (node*)malloc(sizeof(node));p->val = data;while(q->next != NULL)q = q->next;q->next = p;p->next = NULL;returnhead;}node* create_ll(node* head,intdata)// create ll{node* p = (node*)malloc(sizeof(node));p->val = data;if(head == NULL) {head = p;p->next = NULL;returnhead;}else{head = insert_end(head, data);returnhead;}}// Driver codeintmain(){inti = 5, j = 1;while(i--)head = create_ll(head, j++);head = ll_reverse(head);return0;}// This code is contributed by Aditya Kumar (adityakumar129)C
#include<stdio.h>#include<stdlib.h>typedefstructnode {intval;structnode* next;} node;node* head = NULL;// Function to return the No of nodes present in the linked listintcount(node* head){node* p = head;intk = 1;while(p != NULL) {p = p->next;k++;}returnk;}node* ll_reverse(node* head)// to reverse the linked list{node* p = head;longinti = count(head), j = 1;intarr[i];while(i && p != NULL) {arr[j++] = p->val;p = p->next;i--;}j--;while(j)// loop will break as soon as j=0printf("%d ",arr[j--]);returnhead;}// Function to insert node at the end of linked listnode* insert_end(node* head,intdata){node *q = head, *p = (node*)malloc(sizeof(node));p->val = data;while(q->next != NULL)q = q->next;q->next = p;p->next = NULL;returnhead;}node* create_ll(node* head,intdata)// create ll{node* p = (node*)malloc(sizeof(node));p->val = data;if(head == NULL) {head = p;p->next = NULL;returnhead;}else{head = insert_end(head, data);returnhead;}}// Driver codeintmain(){inti = 5, j = 1;while(i--)head = create_ll(head, j++);head = ll_reverse(head);return0;}// This code is contributed by Aditya Kumar (adityakumar129)Java
// Java program of the above approachclassGFG {// Create a class Node to enter values and address in the liststaticclassnode {intval;node next;};staticnode head =null;// code to count the no. of nodesstaticintcount(node head){node p = head;intk =1;while(p !=null) {p = p.next;k++;}returnk;}// to reverse the linked liststaticnode ll_reverse(node head){node p = head;inti = count(head), j =1;int[] arr =newint[i];while(i !=0&& p !=null) {arr[j++] = p.val;p = p.next;i--;}j--;while(j !=0)// loop will break as soon as j=0System.out.print(arr[j--] +" ");returnhead;}// code to insert at end of llstaticnode insert_end(node head,intdata){node q = head;node p =newnode();p.val = data;p.next =null;while(q.next !=null)q = q.next;q.next = p;p.next =null;returnhead;}// create llstaticnode create_ll(node head,intdata){node p =newnode();p.next =null;p.val = data;if(head ==null) {head = p;p.next =null;returnhead;}else{head = insert_end(head, data);returnhead;}}publicstaticvoidmain(String[] args){inti =5, j =1;while(i !=0) {head = create_ll(head, j++);i--;}head = ll_reverse(head);}}// This code is contributed by Aditya Kumar (adityakumar129)C#
// C# program of the above approachusingSystem;publicclassGFG {// Create a class Node to enter// values and address in the listpublicclassnode {publicintval;publicnode next;};staticnode head =null;// code to count the no. of nodesstaticintcount(node head){node p = head;intk = 1;while(p !=null) {p = p.next;k++;}returnk;}// to reverse the linked liststaticnode ll_reverse(node head){node p = head;inti = count(head), j = 1;int[] arr =newint[i];while(i != 0 && p !=null) {arr[j++] = p.val;p = p.next;i--;}j--;while(j != 0)// loop will break as soon as j=0{Console.Write(arr[j--] +" ");}returnhead;}// code to insert at end of llstaticnode insert_end(node head,intdata){node q = head;node p =newnode();p.val = data;p.next =null;while(q.next !=null) {q = q.next;}q.next = p;p.next =null;returnhead;}// create llstaticnode create_ll(node head,intdata){node p =newnode();p.next =null;p.val = data;if(head ==null) {head = p;p.next =null;returnhead;}else{head = insert_end(head, data);returnhead;}}publicstaticvoidMain(String[] args){inti = 5, j = 1;while(i != 0) {head = create_ll(head, j++);i--;}head = ll_reverse(head);}}// This code is contributed by umadevi9616Javascript
<script>// Javascript program of the above approach// Create a class Node to enter values and address in the listclass node {constructor() {this.val =null;this.next =null;}};let head =null;// code to count the no. of nodesfunctioncount(head) {let p = head;let k = 1;while(p !=null) {p = p.next;k++;}returnk;}// to reverse the linked listfunctionll_reverse(head) {let p = head;let i = count(head), j = 1;let arr =newArray(i);while(i != 0 && p !=null) {arr[j++] = p.val;p = p.next;i--;}j--;while(j != 0)// loop will break as soon as j=0document.write(arr[j--] +" ");returnhead;}// code to insert at end of llfunctioninsert_end(head, data) {let q = head;let p =newnode();p.val = data;p.next =null;while(q.next !=null)q = q.next;q.next = p;p.next =null;returnhead;}// create llfunctioncreate_ll(head, data) {let p =newnode();p.next =null;p.val = data;if(head ==null) {head = p;p.next =null;returnhead;}else{head = insert_end(head, data);returnhead;}}let i = 5, j = 1;while(i != 0) {head = create_ll(head, j++);i--;}head = ll_reverse(head);// This code is contributed by gfgking</script>Input : 1->2->3->4->5 Output: 5->4->3->2->1Time complexity: O(N) as we visit every node once.
Auxiliary Space: O(N) as extra space is used to store all the nodes in the array.
Recursively Reversing a linked list (A simple implementation)
Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)References:
http://cslibrary.stanford.edu/105/LinkedListProblems.pdfMy Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :







