forked from NiharRanjan53/HacktoberFest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircular_Linked_List.cpp
87 lines (79 loc) · 1.48 KB
/
Circular_Linked_List.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
#include <iostream>
using namespace std;
class Node {
public:
int val;
Node *next;
Node(int val) {
this->val = val;
next = nullptr;
}
};
class Solution {
Node *head, *tail;
Node *create(int val, Node *head) {
Node *newNode = new Node(val);
if (this->head == nullptr) {
this->head = head = newNode;
}
else {
head->next = newNode;
head = head->next;
}
return head;
}
Node *reverseIterative(Node *head) {
if (head == nullptr) return nullptr;
Node *pre = NULL, *curr = head, *nxt = head;
do {
nxt = curr->next;
curr->next = pre;
pre = curr;
curr = nxt;
} while (curr != head);
head->next = pre;
return pre;
}
Node *reverseRecursive(Node *head, Node *temp) {
if (head == nullptr || temp->next == head) return temp;
Node *restNode = reverseRecursive(head, temp->next);
temp->next->next = temp;
temp->next = restNode;
return restNode;
}
void print(Node *head) {
Node *temp = head;
if (!head) return;
do {
cout << temp->val << ' ';
temp = temp->next;
}
while (temp != head);
cout << '\n';
}
public:
Solution(): head(nullptr), tail(nullptr) {}
void create(int val) {
tail = create(val, tail);
tail->next = head;
}
void reverse() {
// head = reverseIterative(head);
head = reverseRecursive(head, head);
}
void print() {
print(head);
}
};
int main() {
int n; cin >> n;
Solution ob;
for (int i = 0; i < n; ++i) {
int val; cin >> val;
ob.create(val);
}
ob.print();
ob.reverse();
ob.print();
return 0;
}