-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathQueueUsingStack.cpp
67 lines (59 loc) · 1.14 KB
/
QueueUsingStack.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
#include <iostream>
#include <stack>
using namespace std;
class QueueUsingStack{
public:
void push(int key);
int front();
void pop();
bool empty();
private:
stack<int> in_stk;
stack<int> out_stk;
};
void QueueUsingStack::push(int key){
in_stk.push(key);
}
void QueueUsingStack::pop(){
if(!out_stk.empty()){
out_stk.pop();
}else{
while(!in_stk.empty()){
out_stk.push(in_stk.top());
in_stk.pop();
}
if(!out_stk.empty()){
out_stk.pop();
}
}
}
int QueueUsingStack::front(){
if(!out_stk.empty()){
return out_stk.top();
}else{
while(!in_stk.empty()){
out_stk.push(in_stk.top());
in_stk.pop();
}
if(!out_stk.empty()){
return out_stk.top();
}else{
return INT_MAX;
}
}
}
bool QueueUsingStack::empty(){
return in_stk.empty() && out_stk.empty();
}
int main()
{
QueueUsingStack qus;
for(int i = 0; i < 10; ++i){
qus.push(i);
}
while(!qus.empty()){
cout<<qus.front() <<endl;
qus.pop();
}
return 0;
}