-
Notifications
You must be signed in to change notification settings - Fork 1
/
5a) Queue LinkedList.cpp
97 lines (81 loc) · 1.73 KB
/
5a) Queue LinkedList.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
// Linked list implementation of Queue
#include<iostream>
#include "Node.cpp"
using namespace std;
class Queue{
int size;
public:
Node* front;
Node* rear;
Queue(){
front = rear = NULL;
size = 0 ;
}
void enqueue(int);
void dequeue();
int getFront(); // get the element which was added first
bool isempty();
int getSize();
};
bool Queue :: isempty(){
return (front==NULL || rear == NULL);
}
int Queue :: getSize(){
return size;
}
void Queue :: enqueue(int val){
size++;
// Adding at the end of the linked list
Node* newnode = new Node(val);
if(isempty()){
front = rear = newnode;
}
else{
// Insert at end using rear pointer
rear->next = newnode;
rear = newnode;
}
}
void Queue :: dequeue(){
if(!isempty()){
// remove from beginning
// Node* nodetobedelted = front;
front = front->next;
// free(nodetobedelted);
size--;
}
else{
cout << "Queue is empty , nothing to dequeue\n";
front = rear = NULL;
size = 0;
}
}
int Queue :: getFront(){
return (!isempty())? front->data : -1 ;
}
void display(Queue q){
Queue tempQueue = q; // Create a temporary queue to avoid modifying the original
while(!tempQueue.isempty()){
cout << tempQueue.getFront() << " ";
tempQueue.dequeue();
}
cout << endl;
}
int main(){
Queue q;
for(int i=1;i<=5;i++){
q.enqueue(i);
}
display(q);
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
display(q);
q.enqueue(12);
display(q);
cout << endl;
return 0;
}