-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack_implement_from_queue.cpp
More file actions
50 lines (44 loc) · 965 Bytes
/
stack_implement_from_queue.cpp
File metadata and controls
50 lines (44 loc) · 965 Bytes
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
//program to implement stack from queue
//problem link: https://leetcode.com/problems/implement-stack-using-queues
class MyStack {
public:
MyStack() {
}
queue<int>myQ;
queue<int>duplicate;
int tp;
int last,size=0;
void push(int x) {
myQ.push(x);
tp=x;
size++;
}
int pop() {
size--;
while(!myQ.empty())
{
int x=myQ.front();
myQ.pop();
if(!myQ.empty())tp=x;
if(myQ.empty())last = x;
else duplicate.push(x);
}
myQ=duplicate;
return last;
}
int top() {
return tp;
}
bool empty() {
if(size>0)return false;
return true;
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/