-
Notifications
You must be signed in to change notification settings - Fork 178
/
Reverse_Single_LinkedList.cpp
90 lines (68 loc) · 1.95 KB
/
Reverse_Single_LinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Node class represents a node in a linked list
class Node {
public:
int data;
Node* next;
Node(int data1, Node* next1) {
data = data1;
next = next1;
}
Node(int data1) {
data = data1;
next = nullptr;
}
};
// Function to reverse a singly linked list using a recursion
Node* reverseLinkedList(Node* head) {
// Base case:
// If the linked list is empty or has only one node,
// return the head as it is already reversed.
if (head == NULL || head->next == NULL) {
return head;
}
// Recursive step:
// Reverse the linked list starting
// from the second node (head->next).
Node* newHead = reverseLinkedList(head->next);
// Save a reference to the node following
// the current 'head' node.
Node* front = head->next;
// Make the 'front' node point to the current
// 'head' node in the reversed order.
front->next = head;
// Break the link from the current 'head' node
// to the 'front' node to avoid cycles.
head->next = NULL;
// Return the 'newHead,' which is the new
// head of the reversed linked list.
return newHead;
}
// Function to print the linked list
void printLinkedList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
// Create a linked list with
// values 1, 3, 2, and 4
Node* head = new Node(1);
head->next = new Node(3);
head->next->next = new Node(2);
head->next->next->next = new Node(4);
// Print the original linked list
cout << "Original Linked List: ";
printLinkedList(head);
// Reverse the linked list
head = reverseLinkedList(head);
// Print the reversed linked list
cout << "Reversed Linked List: ";
printLinkedList(head);
return 0;
}