Skip to content

Commit c09afb5

Browse files
authored
Merge pull request #177 from kiruba-r11/feature-1
Added Recursive Reverse in Circular Linked Lists
2 parents 703c7bc + 580f705 commit c09afb5

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
3+
This is a Circular Linked List program which reverses the Linked List recursively.
4+
5+
Since, it is a Circular Linked List, the last node would point to the head node.
6+
7+
*/
8+
9+
#include <iostream>
10+
11+
using namespace std;
12+
13+
/*
14+
15+
Node definition:
16+
1. Integer Data
17+
2. Pointer to next node.
18+
19+
*/
20+
21+
class cll_node {
22+
public:
23+
int data;
24+
cll_node* next;
25+
};
26+
27+
void createCLL(cll_node* &head) {
28+
29+
int choice;
30+
31+
cll_node* temp = head;
32+
33+
do {
34+
int data;
35+
36+
cout << "Enter Data : ";
37+
cin >> data;
38+
39+
cll_node* newNode = new cll_node();
40+
newNode->data = data;
41+
newNode->next = NULL;
42+
43+
if(head == NULL) {
44+
head = newNode;
45+
newNode->next = head;
46+
temp = head;
47+
} else {
48+
temp->next = newNode;
49+
temp = newNode;
50+
temp->next = head;
51+
}
52+
53+
cout << "Do you want to continue? (1/0) : ";
54+
cin >> choice;
55+
56+
} while(choice == 1);
57+
58+
}
59+
60+
cll_node* recursive_reverse_helper(cll_node* head , cll_node* tail) {
61+
62+
if(head == NULL || head->next == head)
63+
return head;
64+
65+
// O(1)
66+
/*
67+
// O(n)
68+
// cll_node* tail = head;
69+
// while(tail->next != head) {
70+
// tail = tail->next;
71+
// }
72+
*/
73+
74+
tail->next = head->next;
75+
cll_node* temp = head->next;
76+
77+
cll_node* newHead = recursive_reverse_helper(temp , tail);
78+
79+
temp->next = head;
80+
head->next = newHead;
81+
return newHead;
82+
83+
}
84+
85+
cll_node* recursive_reverse(cll_node* head) {
86+
87+
if(head == NULL || head->next == head)
88+
return head;
89+
90+
cll_node* tail = head;
91+
92+
while(tail->next != head) {
93+
tail = tail->next;
94+
}
95+
96+
return recursive_reverse_helper(head , tail);
97+
}
98+
99+
void display(cll_node* head) {
100+
cout << "The elements are : ";
101+
if(head == NULL)
102+
return;
103+
cll_node* temp = head;
104+
105+
do {
106+
cout << temp->data << " ";
107+
temp = temp->next;
108+
} while(temp != head);
109+
cout << endl;
110+
}
111+
112+
int main() {
113+
114+
cll_node* head = NULL;
115+
116+
createCLL(head);
117+
118+
cout << "Before reversing : " << endl;
119+
display(head);
120+
121+
head = recursive_reverse(head);
122+
123+
cout << "After reversing : " << endl;
124+
display(head);
125+
126+
return 0;
127+
}

0 commit comments

Comments
 (0)