-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedqueue.cpp
88 lines (73 loc) · 1.24 KB
/
linkedqueue.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
#include <iostream>
using namespace std;
struct myNode {
int data;
struct myNode* next;
};
typedef struct myNode Node;
class Queue {
private:
Node* m_front;
Node* m_rear;
public:
Queue();
void enqueue(int data);
int dequeue();
bool isEmpty();
};
Queue::Queue() {
m_front = NULL;
m_rear = NULL;
}
void Queue::enqueue(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
//queue is empty
if(m_front == NULL && m_rear == NULL) {
m_front = m_rear = newNode;
}
else {
m_rear->next = newNode;
m_rear = newNode;
}
return;
}
int Queue::dequeue() {
if(m_front == NULL && m_rear == NULL) {
return -1;
}
int ret = m_front->data;
//single element in queue
if(m_front == m_rear) {
delete m_front;
m_front = m_rear = NULL;
return ret;
}
Node* temp = m_front;
m_front = m_front->next;
delete temp;
return ret;
}
bool Queue::isEmpty() {
if(m_rear == NULL && m_front == NULL)
return true;
return false;
}
int main() {
Queue Q;
int numIns;
cin >> numIns;
while(numIns--) {
int elem;
cin >> elem;
Q.enqueue(elem);
}
while(!Q.isEmpty()) {
cout << Q.dequeue() << endl;
}
cout << Q.dequeue() << endl;
Q.enqueue(3);
cout << Q.dequeue() << endl;
cout << Q.dequeue() << endl;
}