-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularLL.cpp
More file actions
151 lines (127 loc) · 3.01 KB
/
Copy pathCircularLL.cpp
File metadata and controls
151 lines (127 loc) · 3.01 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int data)
{
this->data = data;
this->next = NULL;
}
~node()
{
int value = this->data;
if (this->next!=NULL)
{
delete next;
this->next = NULL;
}
cout<<"(Memory is free for node with data value "<<value<<")"<<endl;
}
};
int getlenght(node* tail)
{
// if list is empty
if (tail==NULL)
return 0;
int cnt = 0;
node* temp= tail;
do
{
cnt++;
temp=temp->next;
}while (temp!=tail);
return cnt;
}
void print(node* tail)
{
// if list is empty
if (tail==NULL)
{
cout<<"List is empty!(Underflow error)"<<endl;
return;
}
node* temp=tail;
cout<<"Elements present in the list are: "<<endl;
do
{
cout<<temp->data<<" ";
temp=temp->next;
}while (temp!=tail);
cout<<endl<<endl;
}
void insertNode(node* &tail, int element, int data)
{
//if list is Empty
if(tail==NULL)
{
node* newNode = new node(data);
tail=newNode;
newNode->next=newNode;
}
else
{
// for non-empty list
// Assuming that the element is present in the list
// Our goal is to insert given 'data' after the given 'element' in the list
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 value)
{
//if list is Empty
if(tail==NULL)
{
cout<<"List is Empty!"<<endl;
return;
}
else
{
// for non-empty list containing unique data values
// Assuming that the element is present in the list
// Our goal is to delete the node with the given 'value' from the List
node* prev=tail;
node* curr=prev->next;
while (curr->data!=value)
{
prev=curr;
curr=curr->next;
}
prev->next=curr->next;
// if only 1 node is present in the list
if(curr==prev)
tail=NULL;
// for >=2 nodes
else if(curr==tail)
tail=prev;
curr->next= NULL;
delete curr;
}
}
int main()
{
node* first = new node(3);
first->next = first; //set next to point to itself, so as to make it cyclic
node* tail = first;
insertNode(tail, 3, 4);
insertNode(tail, 4, 5);
insertNode(tail, 5, 6);
insertNode(tail, 6, 7);
insertNode(tail, 3, 10);
cout<<"Original Stack/Before Deletion: "<<endl;
print(tail);
cout<<"After Deletion: "<<endl;
deleteNode(tail,10);
print(tail);
cout<<"Lenght of stack is "<<getlenght(tail)<<endl;
return 0;
}