-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue2.cpp
86 lines (70 loc) · 1.71 KB
/
Queue2.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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Queue {
private:
Node* front;
Node* rear;
public:
Queue() {
front = nullptr;
rear = nullptr;
}
// ADD operation (enqueue)
void enqueue(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (rear == nullptr) { // Queue is empty
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
cout << "Enqueued: " << value << endl;
}
// DELETE operation (dequeue)
void dequeue() {
if (front == nullptr) { // Queue is empty
cout << "Queue is empty" << endl;
return;
}
Node* temp = front;
cout << "Dequeued: " << front->data << endl;
front = front->next;
if (front == nullptr) { // Queue is now empty
rear = nullptr;
}
delete temp;
}
// Display the elements of the queue
void display() {
if (front == nullptr) {
cout << "Queue is empty" << endl;
return;
}
Node* temp = front;
cout << "Queue elements: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Queue q;
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display();
q.dequeue();
q.display();
q.dequeue();
q.dequeue();
q.dequeue(); // Attempting to dequeue from an empty queue
return 0;
}