Linked list reversal
A linked list is a linear data structure. A node in a linked list consists of:
- Data item.
- The address of the next node.
class Node
{
int data;
Node *next;
};
This article will show you how to reverse a linked list given a pointer to the head node of the linked list.
Linked list reversal algorithm
Let head
be the first node of the linked list.
Iterative Algorithm
-
Initialize 3 pointers -
curr
set tohead
,prev
andnext
set toNULL
. -
Traverse the linked list until you reach the last node, which is
curr
!=NULL
and do the following:-
Set
next
tocurr->next 个
tonext
move to its next node. prev
Reverses the direction of the current node by pointing it toward . Therefore,curr->next
set toprev
.-
Set
prev
tocurr
to move it forward one position. -
Set
curr
tonext
to move it forward one position.
-
Set
Recursive Algorithm
-
Split the list into two parts: the first node, the
head
node, and the rest of the linked list. -
Call
reverse(head->next)
, i.e., the remainder of the reverse linked list, and store the reverse linked list asrev
. -
Append
head
to the end of the reverse-linked listrev
. -
Points to
head
, that is, the tail of the reverse link list points toNULL
Reverse Linked List using Stack
-
Initializes
head
a pointer to a linked listcurr
. - Traverse the linked list and insert each node one by one.
-
Update
head
to the last node in the linked list, which is the first node in the stack. - Start popping nodes from the stack one by one and appending it to the end of the reverse linked list.
-
Update the next pointer of the last node to
NULL
.
Linked list reversal diagram
-
Initialize
curr
to point to the head, that is, nodes2
and ,prev
andcurr
the data of isNULL
. -
Sets
next
to point tocurr->next
a value equal to4
. -
Set
curr->next
toprev
to obtain2
a list of backward links headed by . -
Move
prev
to the nodecurr
with data2
, andcurr
move to the nodenext
with data .4
-
Points
next
tocurr->next
a value equal to6
-
Set
curr->next
toprev
to obtain a reverse linked list with2
and4
as reverse nodes and with4
as the head. -
Move
prev
to , that is, the nodecurr
with data , and move to , that is, the node with data .4
curr
next
6
-
Sets
next
to point tocurr->next
a value equal to8
. -
Set
curr->next
toprev
to obtain a reverse linked list with and2
as reverse nodes and headed by .4
6
6
-
Move
prev
to , that is, the nodecurr
with data , and move to , that is, the node with data .6
curr
next
8
-
Point
next
tocurr->next
, that isNULL
. -
Set
curr->next
toprev
, with2
,4
,6
and8
as reverse nodes and with8
as the head to obtain a reverse linked list. -
Move
prev
tocurr
, that is,8
the node with data , movecurr
toNULL
, and the algorithm terminates.
Implementation of linked list reversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
this->data = x;
this->next = NULL;
}
};
void printList(Node* head)
{
Node*curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
}
Node* reverse(Node* head)
{
Node* curr = head;
Node *prev = NULL, *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
Node* recursiveReverse(Node* head)
{
if (head == NULL || head->next == NULL)
return head;
Node* rest = recursiveReverse(head->next);
head->next->next = head;
head->next = NULL;
return rest;
}
void reverseLL(Node** head)
{
stack<Node*> s;
Node* temp = *head;
while (temp->next != NULL)
{
s.push(temp);
temp = temp->next;
}
*head = temp;
while (!s.empty())
{
temp->next = s.top();
s.pop();
temp = temp->next;
}
temp->next = NULL;
}
int main()
{
Node* head = new Node(1);
head -> next = new Node(2);
head -> next-> next = new Node(3);
head -> next-> next-> next = new Node(4);
head -> next-> next-> next-> next = new Node(5);
head -> next-> next-> next-> next-> next = new Node(6);
head = reverse(head);
printList(head); cout << "\n";
head = recursiveReverse(head);
printList(head); cout << "\n";
reverseLL(&head);
printList(head); cout << "\n";
return 0;
}
Linked list reversal algorithm complexity
Time Complexity
- Average situation
To reverse a complete linked list, we have to visit each node and then append it to the reversal list. Therefore, if a linked list has n
nodes, the average case time complexity of traversal is about O(n)
. The time complexity is about O(n)
.
- Best Case
The time complexity of the best case is O(n)
. It is the same as the time complexity of the average case.
- Worst case scenario
The worst case time complexity is O(n)
. It is the same as the best case time complexity.
Space complexity
The space complexity of this traversal algorithm is O(1)
, since no additional space is required except for the temporary pointers.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Learning the Sorting Algorithm - Insertion Sort (Concepts)
Publish Date:2025/03/19 Views:96 Category:ALGORITHM
-
What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a
Learning path of sorting algorithm - direct insertion sort
Publish Date:2025/03/19 Views:176 Category:ALGORITHM
-
This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide
Learning the sorting algorithm - Binary Insertion Sort
Publish Date:2025/03/19 Views:143 Category:ALGORITHM
-
This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s
The road to learning sorting algorithms - table insertion sort
Publish Date:2025/03/19 Views:194 Category:ALGORITHM
-
Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original
The road to learning sorting algorithms - Hill sort
Publish Date:2025/03/19 Views:52 Category:ALGORITHM
-
Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion
Things about the singleton design pattern
Publish Date:2025/03/19 Views:53 Category:ALGORITHM
-
The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i
The road to learning sorting algorithms - merge sort
Publish Date:2025/03/19 Views:158 Category:ALGORITHM
-
Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt
The road to learning sorting algorithms - merge sort (non-recursive implementatio
Publish Date:2025/03/19 Views:189 Category:ALGORITHM
-
In the article "Merge Sort", we introduced the principles and operation steps of merge sort, and finally implemented the sorting algorithm using PHP code. In the program, we used the principle of recursion to implement the algorithm. In fac
The road to learning sorting algorithms - quick sort
Publish Date:2025/03/19 Views:122 Category:ALGORITHM
-
Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste