-
Notifications
You must be signed in to change notification settings - Fork 6
/
07_QueueWithTwoStacks.cpp
110 lines (92 loc) · 1.46 KB
/
07_QueueWithTwoStacks.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
104
105
106
107
108
109
110
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <stdexcept>
using namespace std;
int push(stack<int> &stack1, int num)
{
stack1.push(num);
return 0;
}
int pop(stack<int> &stack1, stack<int> &stack2)
{
int num;
if (!stack2.empty())
{
num = stack2.top();
stack2.pop();
return num;
}
if (stack1.empty())
return -1;
while (!stack1.empty())
{
num = stack1.top();
stack2.push(num);
stack1.pop();
}
stack2.pop();
return num;
}
template <typename T> class CQueue {
public:
CQueue() {};
~CQueue() {};
void push(const T& node);
T pop();
private:
stack<T> stack1;
stack<T> stack2;
};
template<typename T> void CQueue::push(const T& node) {
stack1.push(node);
}
template<typename T> T CQueue::pop() {
if(stack2.empty()) {
while(!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
if(stack2.empty()) {
throw runtime_error("The Queue is empty.");
}
T node = stack2.top();
stack2.pop();
return node;
}
int main(void)
{
/*int n, num;
string cmds;
stack<int> stack1;
stack<int> stack2;
cin >> n;
while (n --)
{
cin >> cmds;
if (cmds == "PUSH")
{
cin >> num;
push(stack1, num);
}
if (cmds == "POP")
{
num = pop(stack1, stack2);
cout << num << endl;
}
}*/
cin >> n;
CQueue<int> myQueue;
myQueue.push(1);
myQueue.push(3);
myQueue.pop();
myQueue.push(4);
myQueue.push(5);
myQueue.pop();
myQueue.pop();
myQueue.pop();
myQueue.pop();
return 0;
}