-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingQueue
More file actions
40 lines (35 loc) · 1.21 KB
/
StackUsingQueue
File metadata and controls
40 lines (35 loc) · 1.21 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
class MyStack {
public:
//INITIALISE THE DATA STRUCTRURE HERE
queue<int> q;//QUEUE IMPLEMETED
MyStack() {
}
//PUSH ELEMENT ONTO THE STACK
void push(int x) {
if(q.empty()) q.push(x);//IF EMPTY THEN DIRECT PUSH
else{
int s=q.size();//SIZE OF QUEUE
q.push(x);//PUSHING OF ELEEMNT
while(s--){//WHILE S--
int top=q.front();//TOP ELEEMTN QUEUE KA
q.pop();//REMOVE THAT ELEMENT AS FIRST IN FIRST OUT FOLLOWED
q.push(top);//PUSH IN QUEUE AS FOR CHANGING INTO LAST IN FIRST OUT TYPE STACK
}//LAST IN FIRST OUT KRWA RHE H OKKK PICHE SE NIKAL WA RHE H AND WAPIS USKO ADD KR RHE H
}
}
//REMOVES THE ELEMENT ON THE TOP OF THE STACK AND RETURNS THE ELEMT
int pop() {
int top=q.front();//TOPMOST ELEMTN IS THE FRONT ELEMET OF QUEUE
q.pop();//POP
return top;//RETURN THE TOPMOST ELEMENT
}
//GETS THE TOP ELEMENT
int top() {
return q.front();//TOPMOST ELEMETN DIREFT
}
//CHECKS WHETER THE STACK IS EMPTY OR NOT
bool empty() {
if(q.empty()) return true;
else return false;
}
};