-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathCircularLinkedList.cpp
More file actions
89 lines (72 loc) · 1.53 KB
/
Copy pathCircularLinkedList.cpp
File metadata and controls
89 lines (72 loc) · 1.53 KB
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>
using namespace std;
class Node{
public:
int data;
Node* next;
};
class CircularLinkedList{
private:
Node* head;
public:
CircularLinkedList(int A[], int n);
void Display();
void recursiveDisplay(Node* p);
Node* getHead(){ return head; }
~CircularLinkedList();
};
CircularLinkedList::CircularLinkedList(int *A, int n) {
Node* t;
Node* tail;
head = new Node;
head->data = A[0];
head->next = head;
tail = head;
for (int i=1; i<n; i++){
t = new Node;
t->data = A[i];
t->next = tail->next;
tail->next = t;
tail = t;
}
}
void CircularLinkedList::Display() {
Node* p = head;
do {
cout << p->data << " -> " << flush;
p = p->next;
} while (p != head);
cout << endl;
}
void CircularLinkedList::recursiveDisplay(Node *p) {
static int flag = 0;
if (p != head || flag == 0){
flag = 1;
cout << p->data << " -> " << flush;
recursiveDisplay(p->next);
}
flag = 0;
}
CircularLinkedList::~CircularLinkedList() {
Node* p = head;
while (p->next != head){
p = p->next;
}
while (p != head){
p->next = head->next;
delete head;
head = p->next;
}
if (p == head){
delete head;
head = nullptr;
}
}
int main() {
int A[] = {1, 3, 5, 7, 9};
CircularLinkedList cl(A, sizeof(A)/sizeof(A[0]));
cl.Display();
Node* h = cl.getHead();
cl.recursiveDisplay(h);
return 0;
}