-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcircular_linkedlist.cpp
139 lines (115 loc) · 2.56 KB
/
circular_linkedlist.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
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
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
//constructor
node(int data){
this -> data = data;
this -> next = NULL;
}
};
//insert a node at head
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{
//non empty list
node* curr = tail;
while(curr -> data != element){
curr = curr -> next;
}
//element found
node* temp = new node(data);
temp -> next = curr -> next;
curr -> next = temp;
}
}
//delete a node
void deleteNode(node* &tail,int value){
//empty list
if(tail == NULL){
cout<<"List empty"<<endl;
return;
}
else{
//non empty list
node* prev=tail;
node* curr=prev->next;
while(curr -> data != value){
prev=curr;
curr=curr->next;
}
prev->next = curr->next;
//1 noode only
if(curr==prev){
tail=NULL;
}
//2 or more node
if(tail==curr){
tail=prev;
}
curr->next=NULL;
delete curr;
}
}
//traversing a linked list
void print(node* &tail){
node* temp = tail;
if(tail==NULL){
cout<<"list is empty"<<endl;
return;
}
do{
cout << tail -> data << " ";
tail = tail -> next;
}while(tail != temp);
cout<<endl;
}
//linked list circular or not
bool isCircularList(node* head){
if(head==NULL){
return true;
}
node* temp=head->next;
while(temp!=NULL && temp!=head){
temp=temp->next;
}
if(temp==head){
return true;
}
else{
return false;
}
}
int main(){
node* tail = NULL;
InsertNode(tail,5,3);
print(tail);
// InsertNode(tail,3,5);
// print(tail);
// InsertNode(tail,5,7);
// print(tail);
// InsertNode(tail,7,9);
// print(tail);
// InsertNode(tail,5,6);
// print(tail);
// InsertNode(tail,9,10);
// print(tail);
// InsertNode(tail,3,4);
// print(tail);
// deleteNode(tail,3);
// print(tail);
if(isCircularList(tail)){
cout<<"linked list is circular list"<<endl;
}
else{
cout<<"linked list is not circular"<<endl;
}
return 0;
}