-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueuelinkedlist.cpp
90 lines (73 loc) · 1.75 KB
/
queuelinkedlist.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
#include <iostream>
using namespace std;
// Define the structure of each node in the linked list
struct Node {
int data;
Node* next;
};
// Define the queue class
class Queue {
private:
Node* front;
Node* rear;
public:
Queue() {
front = NULL;
rear = NULL;
}
// Function to check if the queue is empty
bool isEmpty() {
return (front == NULL && rear == NULL);
}
// Function to add an element to the rear of the queue
void enqueue(int x) {
Node* newNode = new Node;
newNode->data = x;
newNode->next = NULL;
if (isEmpty()) {
front = rear = newNode;
return;
}
rear->next = newNode;
rear = newNode;
}
// Function to remove an element from the front of the queue
void dequeue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
if (front == rear) {
front = rear = NULL;
} else {
Node* temp = front;
front = front->next;
delete temp;
}
}
// Function to display the elements of the queue
void display() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
Node* temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
// Driver program to test the queue implementation
int main() {
Queue q;
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display();
q.dequeue();
q.dequeue();
q.display();
return 0;
}