-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program for linked list representation of linear queue.cpp
102 lines (94 loc) · 2.21 KB
/
Program for linked list representation of linear queue.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
#include <iostream>
using namespace std;
// Define a structure for the node
struct Node {
int data;
Node* next;
};
// Define a class for the queue
class Queue {
private:
Node* front;
Node* rear;
public:
// Constructor
Queue() {
front = NULL;
rear = NULL;
}
// Function to check if the queue is empty
bool isEmpty() {
return (front == NULL);
}
// Function to enqueue an element to the queue
void enqueue(int x) {
Node* temp = new Node;
temp->data = x;
temp->next = NULL;
if (front == NULL && rear == NULL) {
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
// Function to dequeue an element from the queue
void dequeue() {
Node* temp = front;
if (front == NULL) {
cout << "Queue is empty" << endl;
return;
}
if (front == rear) {
front = rear = NULL;
}
else {
front = front->next;
}
delete temp;
}
// Function to display the queue
void display() {
Node* temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Function to get the front element of the queue
int frontElement() {
if (front == NULL) {
cout << "Queue is empty" << endl;
return -1;
}
return front->data;
}
};
int main() {
// Create an object of the Queue class
Queue q;
// Enqueue elements to the queue
q.enqueue(5);
q.enqueue(10);
q.enqueue(15);
q.enqueue(20);
// Display the queue
cout << "Queue elements: ";
q.display();
// Dequeue an element from the queue
q.dequeue();
// Display the queue after dequeuing an element
cout << "Queue elements: ";
q.display();
// Get the front element of the queue
cout << "Front element of the queue: " << q.frontElement() << endl;
// Check if the queue is empty
if (q.isEmpty()) {
cout << "Queue is empty" << endl;
}
else {
cout << "Queue is not empty" << endl;
}
return 0;
}