-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue implementation - linkedlist.cpp
159 lines (143 loc) · 3.05 KB
/
queue implementation - 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// don't need any size
#include<bits/stdc++.h>
using namespace std;
template<class t>
class linkedQueue
{
private:
struct node
{
t item;
node *next;
};
node *frontPtr;
node *rearPtr;
int length;
public:
//constructor
linkedQueue()
{
frontPtr = rearPtr = NULL;
length = 0;
}
//is empty function
bool isEmpty()
{
//return length == 0;
if (rearPtr == NULL)
return true;
else
return false;
}
//addition function
void enqueue(t element)
{
if(isEmpty()){
frontPtr = new node;
frontPtr -> item = element;
frontPtr -> next = NULL;
rearPtr = frontPtr;
length++;
}
else{
node *newPtr = new node;
newPtr -> item = element;
newPtr -> next = NULL;
rearPtr -> next = newPtr;
rearPtr = newPtr;
length++;
}
}
void dequeue()
{
if(isEmpty())
cout << "Empty queue!";
else if(length == 1){
delete frontPtr;
rearPtr = NULL;
length = 0;
}
else{
node *tempPtr =frontPtr;
frontPtr = frontPtr -> next;
delete tempPtr;
length--;
}
}
t getFront()
{
assert(!isEmpty());
return frontPtr -> item;
}
t getRear()
{
assert(!isEmpty());
return rearPtr -> item;
}
/*
void getFront2(int &el){
el = frontPtr -> item;
}
*/
void clearQue()
{
node *currentPtr;
while(frontPtr != NULL){
currentPtr = frontPtr;
frontPtr = frontPtr -> next;
delete currentPtr;
}
rearPtr = NULL;
length = 0;
}
void displayQue()
{
node *currentPtr = frontPtr;
cout << "Items in the queue: [";
while(currentPtr != NULL){
cout << currentPtr -> item << " ";
currentPtr = currentPtr -> next;
}
cout << "]" << endl;
}
int getSize()
{
return length;
}
void searchQue(t item)
{
node *currentPtr = frontPtr;
bool flag = true;
while(currentPtr != NULL){
if(currentPtr -> item == item){
cout << "The item: "<< item << " is found" << endl;
flag = false;
break;
}
currentPtr = currentPtr -> next;
}
if(flag)
cout << "the item: " << item << " is not found" << endl;
}
};
int main()
{
linkedQueue<char>q1;
q1.enqueue('A');
q1.enqueue('B');
q1.enqueue('C');
q1.dequeue();
q1.searchQue('B');
q1.searchQue('A');
cout << "front = " << q1.getFront() << endl;
cout << "rear = " << q1.getRear() << endl;
q1.displayQue();
q1.clearQue();
q1.displayQue();
cout << q1.getSize() << endl;
}
//Time complexity
/*
addition & deletion = const time
search = linear time
*/