Reverse a linked list using C++
In this article, we need to reverse the link with the help of a singly linked list. Our task is to create a function that can reverse a given singly linked list. For example
Input: Following Linked list : 1->2->3->4->NULL Output: After processing of our function: 4->3->2->1->NULL
Methods to find solution
There are different ways to reverse a linked list. Usually, we think of a simple way of reversing the linked list while traversing it.
Simple Method
In this method, we will traverse the linked list and try to reverse it during the traversal.
Example
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } // Function to print linked list void reverse() { auto curr = head; // current pointer Node* prev = NULL; // previous pointer while(curr) { auto temp = curr -> next; curr -> next = prev; prev = curr; head = prev; curr = temp; } } void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; int main() { LinkedList list; list.push(20); list.push(4); list.push(15); list.push(85); list.print(); list.reverse(); cout << "\n"; list.print(); }
Output
85 15 4 20 20 4 15 85
In this approach, we just iterate through the list and reverse it during the iteration. This is a good approach because the time complexity is O(N), where N is the size of our list.
Now we try to do an experiment and try to reverse the list using the stack.
Methods using stack
We will use a stack to store all the nodes in this program and reverse them by traversing the stack.
Example
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } // Function to print linked list void reverse() { auto curr = head; // current pointer Node* prev = NULL; // previous pointer stack<Node *> s; while(curr) { s.push(curr); curr = curr -> next; } prev = s.top(); head = prev; s.pop(); while(!s.empty()) { auto temp = s.top(); s.pop(); prev -> next = temp; prev = temp; } prev -> next = NULL; } void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; int main() { LinkedList list; list.push(20); list.push(4); list.push(15); list.push(85); list.print(); list.reverse(); cout << "\n"; list.print(); }
Output
85 15 4 20 20 4 15 85
Explanation of the above code
In this method we store the list nodes in the stack while traversing the list , then use the stack to pop them and reverse the list; the time complexity of this approach is also O(N), where N is our list size. As before, we used the stack, so we can also use the recursive method, because recursion also uses the stack, and now we will use the recursive method.
Recursive Method
In this method we will perform the same process as before but using recursive calls.
Example
#include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } // Function to print linked list void rreverse(Node *curr, Node *prev) { if(curr == NULL) { // prev -> next = curr; head = prev; return; } rreverse(curr -> next, curr); curr -> next = prev; prev -> next = NULL; } void reverse() { auto curr = head; // current pointer Node* prev = NULL; // previous pointer rreverse(curr -> next, curr); } void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; int main() { LinkedList list; list.push(20); list.push(4); list.push(15); list.push(85); list.print(); list.reverse(); cout << "\n"; list.print(); }
Output
85 15 4 20 20 4 15 85
In this method we are doing the same as before but using recursive calls so the time complexity of this method is also O(N), where N is the size of our list.
Conclusion
In this article, we solved the problem of inverting a singly linked list. We also learned the C program and the complete method (normal method and two other methods) to solve this problem. We can write the same program in other languages like C, Java, Python and others. Hope you find this article helpful.
The above is the detailed content of Reverse a linked list using C++. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

In this article, we will learn about the reversal algorithm to rotate a given array to the right by k elements, for example −Input:arr[]={4,6,2,6,43,7,3,7},k= 4Output:{43,7,3,7,4,6,2,6}Explanation:Rotatingeachelementofarrayby4-elementtotherightgives{43,7,3,7,4,6,2,6}.Input:arr[]={8 ,5,8,2,1,4,9,3},k=3Output:{4,9,3,8,5,8,2,1} Find the solution

A circle is a closed figure. All points on a circle are equidistant from a point inside the circle. The center point is called the center of the circle. The distance from a point to the center of a circle is called the radius. Area is a quantitative representation of the span of dimensions of a closed figure. The area of a circle is the area enclosed within the dimensions of the circle. The formula to calculate the area of a circle, Area=π*r*r To calculate the area, we give the radius of the circle as input, we will use the formula to calculate the area, algorithm STEP1: Takeradiusasinputfromtheuserusingstdinput.STEP2: Calculatetheareaofcircleusing, area=(

In this article we will describe all possible ways to find quaternions, using A.P. for the first 3 terms and G.P. for the last 3 terms. First, we will explain the basic definitions of arithmetic progression (A.P.) and geometric progression (G.P.). Arithmetic Progression (A.P.) - It is a sequence of numbers in which the common difference (d) is the same or constant, meaning that the difference of two consecutive numbers is constant. For example: 1,3,5,7,9|d=2 Geometric Progression (G.P.) - This is a sequence of numbers where the common ratio (r) is the same, which means we can multiply the previous number with a fixed number. For example: 3, 6, 12, 24, ....|r=2 In this problem, we need to determine how many are in the array arr[] of N integers

In this article, we will use C++ to solve the problem of finding the number of subarrays whose maximum and minimum values are the same. The following is an example of the problem −Input:array={2,3,6,6,2,4,4,4}Output:12Explanation:{2},{3},{6},{6},{2 },{4},{4},{4},{6,6},{4,4},{4,4}and{4,4,4}arethesubarrayswhichcanbeformedwithmaximumandminimumelementsame.Input:array={3,3, 1,5,

In this problem, we are given a pointer to the head of the linked list and an integer k. In a group of size k, we need to reverse the linked list. For example -Input:1<->2<->3<->4<->5(doublylinkedlist),k=3Output:3<->2<->1<->5<->4 looking for solutions Method In this problem, we will formulate a recursive algorithm to solve this problem. In this method we will use recursion and solve the problem using recursion. Example#include<iostream&

We need proper knowledge to create several unique pairs in array syntax of C++. While finding the number of unique pairs, we count all the unique pairs in the given array i.e. all possible pairs can be formed where each pair should be unique. For example -Input:array[]={5,5,9}Output:4Explanation:Thenumberoffalluniquepairsare(5,5),(5,9),(9,5)and(9,9).Input:array[]= {5,4,3,2,2}Output:16 Ways to Find Solution There are two ways to solve this problem, they are −

In this article we will explain ways to find reflexive relations on a set. In this problem, we are given a number n, and a set of n natural numbers, and we must determine the number of reflexive relations. Reflexive relation - A relation R is said to be a reflexive relation on the set A if for every 'a' in the set A, (a, a) belongs to the relation R. For example -Input:x=1Output:1Explanation:set={1},reflexiverelationsonA*A:{{1}}Input:x=2Output:4Explanation:set={1,2},reflexiverelationsonA*
