-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7_QueueWithTwoStacks.cpp
56 lines (50 loc) · 965 Bytes
/
7_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
#include <iostream>
#include <stack>
using namespace std;
template <typename T> class CQueue
{
public:
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template <typename T>
void CQueue<T>::appendTail(const T& node)
{
stack1.push(node);
}
template <typename T>
T CQueue<T>::deleteHead()
{
if (!stack2.empty())
{
T temp = stack2.top();
stack2.pop();
return temp;
}
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
T node = stack2.top();
stack2.pop();
return node;
}
int main()
{
CQueue<int> q;
q.appendTail(9);
q.appendTail(8);
q.appendTail(7);
q.appendTail(6);
q.appendTail(5);
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
cout << q.deleteHead() << endl;
return 0;
}