forked from AhmadEnan/Data-Structures-Project-01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.cpp
More file actions
66 lines (60 loc) · 2.15 KB
/
Copy pathQueue.cpp
File metadata and controls
66 lines (60 loc) · 2.15 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
#include "Queue.h"
#include <iostream>
using namespace std;
// ===== Member 4: QueueArray =================================================
// Implement QueueArray methods in this section.
// Remember to explain circular index wrapping logic with meaningful comments.
// ===== Member 5: QueueLinkedList ===========================================
// Implement QueueLinkedList methods in this section.
QueueLinkedList::QueueLinkedList()
{
front = nullptr;
rear = nullptr;
}
QueueLinkedList::~QueueLinkedList() // to free all nodes in queue to avoid memory leak , we loop through list and delete every node
{
while (front != nullptr) {
Node* temp = front;
front = front->next;
delete temp;
}
rear = nullptr;
}
bool QueueLinkedList::isEmpty() const // queue is empty if front is null
{
return front == nullptr;
}
void QueueLinkedList::enqueue(int value) //we add new element at the end and if it is empty front and rear will both point to new node otherwise new node is added after rear and rear is moved forward
{
Node* newNode = new Node(value);
if (isEmpty()) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
int QueueLinkedList::dequeue() //we remove element from front and return its value if queue is empty we return -1 otherwise we store front node in temp variable move front to next node and if front becomes null we set rear to null as well then we delete temp node and return its value
{
if (isEmpty()) {
return -1; // Return -1 to indicate the queue is empty. In a real implementation, consider throwing an exception or using a more robust error handling mechanism.
}
Node* temp = front;
int value = temp->data;
front = front->next;
if (front == nullptr)
{
rear = nullptr; // If the queue becomes empty, set rear to nullptr as well.
}
delete temp;
return value;
}
void QueueLinkedList::display() const //print all elements from front to rear
{
Node* current = front;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}