-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircularLL_implementation.cpp
More file actions
123 lines (110 loc) · 2.16 KB
/
Copy pathcircularLL_implementation.cpp
File metadata and controls
123 lines (110 loc) · 2.16 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
// constructor
Node(int d)
{
this->data = d;
this->next = NULL;
}
// destructor
~Node()
{
int val = this->data;
if (this->next != NULL)
{
this->next = NULL;
delete next;
}
cout << "memoery is free with data" << val << endl;
}
};
void insertNode(Node *&tail, int element, int data)
{
// for empty node
if (tail == NULL)
{
Node *newNode = new Node(data);
tail = newNode;
newNode->next = newNode;
}
// assuming there exists an element in the LL
else
{
Node *curr = tail;
while (curr->data != element)
{
curr = curr->next;
}
Node *temp = new Node(data);
temp->next = curr->next;
curr->next = temp;
}
}
void deleteNode(Node *&tail, int element)
{
if (tail == NULL)
{
cout << "LL is empty" << endl;
}
else
{
Node *prev = tail;
Node *curr = prev->next;
while (curr->data != element)
{
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
// 1 node in linked list
if (curr == prev)
{
tail = NULL;
}
//>=2 linked list
if (tail == curr)
{
tail = prev;
}
curr->next = NULL;
delete curr;
}
}
// traversal in cricular LL
void display(Node *&tail)
{
if (tail == NULL)
{
cout << "linked list is empty." << endl;
}
Node *temp = tail;
do
{
cout << tail->data << " ";
tail = tail->next;
} while (tail != temp);
cout << endl;
}
int main()
{
Node *tail = NULL;
insertNode(tail, 3, 5);
display(tail);
insertNode(tail, 5, 15);
display(tail);
// insertNode(tail, 5, 10);
// display(tail);
// insertNode(tail, 10, 7);
// display(tail);
// insertNode(tail, 15, 2);
// display(tail);
// cout << tail->data << endl;
deleteNode(tail, 5);
display(tail);
return 0;
}