To reverse a linked list, we can use a three-pointer approach. We initialize three pointers: prev
, current
, and next
. Initially, prev
and next
are set to nullptr
and current
is set to the head of the linked list.
We then iterate through the linked list, updating the next
pointer of the current node to point to the previous node. This way, we reverse the direction of the links.
Here's the C++ code for reversing a linked list using this approach:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Linked List Node
5class Node {
6public:
7 int data;
8 Node* next;
9
10 Node(int value) {
11 data = value;
12 next = nullptr;
13 }
14};
15
16// Linked List Class
17class LinkedList {
18public:
19 Node* head;
20
21 LinkedList() {
22 head = nullptr;
23 }
24
25 // Reversing a Linked List
26 void reverseList() {
27 Node* prev = nullptr;
28 Node* current = head;
29 Node* next = nullptr;
30
31 while (current != nullptr) {
32 next = current->next;
33 current->next = prev;
34 prev = current;
35 current = next;
36 }
37
38 head = prev;
39 }
40};
41
42int main() {
43 // Create a Linked List
44 LinkedList list;
45 list.head = new Node(1);
46 list.head->next = new Node(2);
47 list.head->next->next = new Node(3);
48 list.head->next->next->next = new Node(4);
49
50 // Print the original Linked List
51 Node* current = list.head;
52 while (current != nullptr) {
53 cout << current->data << " ";
54 current = current->next;
55 }
56
57 cout << endl;
58
59 // Reverse the Linked List
60 list.reverseList();
61
62 // Print the reversed Linked List
63 current = list.head;
64 while (current != nullptr) {
65 cout << current->data << " ";
66 current = current->next;
67 }
68
69 cout << endl;
70
71 return 0;
72}
xxxxxxxxxx
72
}
using namespace std;
// Linked List Node
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
}
};
// Linked List Class
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
// Reversing a Linked List
void reverseList() {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment