-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement Queue using Linked List.cpp
103 lines (89 loc) · 1.57 KB
/
Implement Queue using Linked List.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
103
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
struct QueueNode
{
int data;
QueueNode *next;
QueueNode(int a)
{
data = a;
next = NULL;
}
};
struct MyQueue {
QueueNode *front;
QueueNode *rear;
void push(int);
int pop();
MyQueue() {front = rear = NULL;}
};
int main()
{
int T;
cin>>T;
while(T--)
{
MyQueue *sq = new MyQueue();
int Q;
cin>>Q;
while(Q--){
int QueryType=0;
cin>>QueryType;
if(QueryType==1)
{
int a;
cin>>a;
sq->push(a);
}else if(QueryType==2){
cout<<sq->pop()<<" ";
}
}
cout<<endl;
}
}
// } Driver Code Ends
/* Structure of a node in Queue
struct QueueNode
{
int data;
QueueNode *next;
QueueNode(int a)
{
data = a;
next = NULL;
}
};
And structure of MyQueue
struct MyQueue {
QueueNode *front;
QueueNode *rear;
void push(int);
int pop();
MyQueue() {front = rear = NULL;}
}; */
/* The method push to push element into the queue*/
void MyQueue:: push(int x)
{
QueueNode* temp = new QueueNode(x);
if(front == NULL)
{
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
/*The method pop which return the element
poped out of the queue*/
int MyQueue :: pop()
{
if(front==NULL)
{
return -1;
}
QueueNode* temp = front;
front = front->next;
temp->next = NULL;
return temp->data;
}