-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue_using_linked_list.cpp
More file actions
118 lines (102 loc) · 2.92 KB
/
Copy pathQueue_using_linked_list.cpp
File metadata and controls
118 lines (102 loc) · 2.92 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 <iostream>
using namespace std;
// Node structure
struct Node {
int data;
struct Node* next;
};
// Pointers for the queue
struct Node* front = NULL;
struct Node* rear = NULL;
// Function to create a new node
struct Node* createNode(int item) {
struct Node* ptr = new Node; // Use new instead of malloc
ptr->data = item;
ptr->next = NULL;
return ptr;
}
// Function to enqueue an element into the queue
void enqueue(int item) {
struct Node* ptr = createNode(item);
if (front == NULL) {
front = rear = ptr; // If queue is empty, front and rear are the same
} else {
rear->next = ptr; // Link the new node to the current rear
rear = ptr; // Update the rear pointer
}
cout << item << " enqueued into the queue." << endl;
}
// Function to dequeue an element from the queue
void dequeue() {
struct Node* temp = front;
cout << front->data << " dequeued from the queue." << endl;
front = front->next; // Move front to the next node
if (front == NULL) { // If the queue becomes empty
rear = NULL;
}
delete temp; // Use delete instead of free
}
// Function to get the front element of the queue
int peek() {
return front->data;
}
// Function to display the queue
void display() {
struct Node* temp = front;
cout << "Queue: ";
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Menu-driven main function
int main() {
int choice, item;
while (true) {
cout << "\nMenu:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Peek\n";
cout << "4. Display Queue\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the element to enqueue: ";
cin >> item;
enqueue(item);
display();
break;
case 2:
if (front == NULL) {
cout << "Queue is empty. Cannot dequeue!" << endl;
} else {
dequeue();
display();
}
break;
case 3:
if (front == NULL) {
cout << "Queue is empty. Nothing to peek!" << endl;
} else {
cout << "Front element is: " << peek() << endl;
}
break;
case 4:
if (front == NULL) {
cout << "Queue is empty. Nothing to display!" << endl;
} else {
display();
}
break;
case 5:
cout << "Exiting program..." << endl;
exit(0);
default:
cout << "Invalid choice! Please try again." << endl;
}
}
return 0;
}