-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.cpp
More file actions
118 lines (102 loc) · 2.72 KB
/
Copy pathQueue.cpp
File metadata and controls
118 lines (102 loc) · 2.72 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
#include "Queue.h"
#include <iostream>
using namespace std;
//circular queue using array
QueueArray::QueueArray(int size) {
capacity = size;
arr = new int[capacity];
front = -1;
rear = -1;
count = 0;
}
QueueArray::~QueueArray() {
delete[] arr;
cout << "QueueArray destroyed." << endl;
}
bool QueueArray::isEmpty() {
if (front == -1 && rear == -1) return true;
else return false;
}
bool QueueArray::isFull() {
if ((rear + 1) % capacity == front) return true;//front=0, rear=2 ->(2 + 1) % 3 = 0 == front >>> FULL
else return false;
}
void QueueArray::enqueue(int data) {
if (isFull()) {
cout << "Queue is Full! Cannot add " << data << endl;
return;
}
else if (isEmpty()) {
rear = front = 0;//means exactly 1 item
arr[rear] = data;
count++; // first item added
cout << data << " enqueued to queue" << endl;
}
else {
rear = (rear + 1) % capacity; // next step,wraps back to start
arr[rear] = data;
count++;
cout << data << " enqueued to queue" << endl;
}
}
int QueueArray::dequeue() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return -1; //nothing valid was returned, an error occurred
}
int val;
if (front == rear) {//1 item only
val = arr[front];
front = rear = -1;//empty
count--; // last item removed
}
else {
val = arr[front];
front = (front + 1) % capacity;//moving forward
count--;
}
return val;
}
// QUEUE lINKED lIST
QueueLinkedList::QueueLinkedList() {
front = nullptr;
rear = nullptr;
}
QueueLinkedList::~QueueLinkedList() {
while (front != nullptr) {
Node* temp = front;// save current front
front = front->next;//move front to next node
delete temp;// delete the saved node
}
}
bool QueueLinkedList::isEmpty() {
return front == nullptr;
}
void QueueLinkedList::enqueue(int data) {
Node* newNode = new Node; //ifEmpty newNode=FirstNode
newNode->data = data;
newNode->next = nullptr;
if (isEmpty()) {
front = newNode;
rear = newNode;
//both points to FirstNode
}
else {
rear->next = newNode;//creating new node
rear = newNode;//moving the rear to the new node
}
}
int QueueLinkedList::dequeue() {
if (isEmpty()) {
cout << "Queue is Empty!" << endl;
return -1;
}
Node* temp = front;
int val = temp->data;
front = temp->next;//FIFO
if (front == nullptr) {
rear = nullptr;//isEmpty checked
}
delete temp;
return val;
}