This repository has been archived by the owner on Dec 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Queue using Linked List in c++
145 lines (119 loc) · 1.6 KB
/
Queue using Linked List in c++
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
class Queue
{
public:
Node* front;
Node*rear;
Queue()
{
front = NULL;
rear = NULL;
}
bool isEmpty()
{
if((front==NULL) && (rear==NULL))
{
return true;
}
else
return false;
}
void Enqueue(Node* n)
{
if(isEmpty())
{
front = n;
rear = n;
cout<<"Enqueued Successfully"<<endl;
}
else
{
rear->next = n;
rear = n;
cout<<"Node Enqueued succesfully"<<endl;
}
}
Node* Dequeue()
{
Node* temp = NULL;
if(isEmpty())
{
cout<<"Queue is empty"<<endl;
return NULL;
}
else
{
if(front==rear)
{
temp = front;
front=NULL;
rear=NULL;
return temp;
}
else
{
temp = front;
front=front->next;
return temp;
}
}
}
int CountNoOfNodes()
{
int count=0;
Node* temp = front;
while(temp!=NULL)
{
count++;
temp = temp->next;
}
return count;
}
void display()
{
if(isEmpty())
{
cout<<"Queue is Empty"<<endl;
return;
}
Node* temp = front;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp= temp->next;
}
cout<<endl;
}
};
int main()
{
Node* n1 = new Node(4);
Node* n2 = new Node(5);
Node* n3 = new Node(6);
Node* n4 = new Node(7);
Node* n5 = new Node(8);
Queue q;
q.Enqueue(n1);
q.Enqueue(n2);
q.Enqueue(n3);
q.Enqueue(n4);
q.Enqueue(n5);
q.display();
cout<<"\n\n AFTER DEQUEUED"<<endl<<endl;
q.Dequeue();
q.display();
cout<<"\n\nCount no of nodes"<<endl<<endl;
cout<<q.CountNoOfNodes();
}