-
Notifications
You must be signed in to change notification settings - Fork 1
/
stackwith2qs.cpp
102 lines (86 loc) · 2.06 KB
/
stackwith2qs.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
// {"category": "Stack", "notes": "Stack with two queues"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <queue>
using namespace std;
//------------------------------------------------------------------------------
//
// Please design a stack with two queues and implement the methods to push and
// pop items.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
template<class Object>
class Stack
{
public:
void Push(const Object& object);
Object Pop();
private:
queue<Object> m_queue1;
queue<Object> m_queue2;
};
template<class Object>
void Stack<Object>::Push(const Object& object)
{
if (m_queue2.empty())
{
m_queue1.push(object);
}
else
{
m_queue2.push(object);
}
}
template<class Object>
Object Stack<Object>::Pop()
{
queue<Object>* pEmptyQueue;
queue<Object>* pNonEmptyQueue;
if (m_queue2.empty())
{
pEmptyQueue = &m_queue2;
pNonEmptyQueue = &m_queue1;
}
else
{
pEmptyQueue = &m_queue1;
pNonEmptyQueue = &m_queue2;
}
if (!pEmptyQueue->empty() ||
pNonEmptyQueue->empty())
{
throw exception();
}
while (pNonEmptyQueue->size() > 1)
{
pEmptyQueue->push(pNonEmptyQueue->front());
pNonEmptyQueue->pop();
}
Object object = pNonEmptyQueue->front();
pNonEmptyQueue->pop();
return object;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
Stack<int> intStack;
intStack.Push(3);
intStack.Push(1);
cout << intStack.Pop() << " ";
intStack.Push(2);
cout << intStack.Pop() << " ";
cout << intStack.Pop() << " ";
cout << endl;
return 0;
}