-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path225_ImplementStackUsingQueues.cpp
More file actions
132 lines (118 loc) · 2.76 KB
/
Copy path225_ImplementStackUsingQueues.cpp
File metadata and controls
132 lines (118 loc) · 2.76 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
//两个队列实现一个栈
class MyStack {
private:
queue<int> que1, que2;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que2.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if (que2.empty()){
int temp = que1.front();
que1.pop();
while (!que1.empty()){
que2.push(temp);
temp = que1.front();
que1.pop();
}
return temp;
}
else{
int temp = que2.front();
que2.pop();
while (!que2.empty()){
que1.push(temp);
temp = que2.front();
que2.pop();
}
return temp;
}
}
/** Get the top element. */
int top() {
int x = pop();
if (!que1.empty())
que1.push(x);
else
que2.push(x);
return x;
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.empty() && que2.empty();
}
};
/**
* 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();
*/
class MyStack2 {
public:
queue<int> que1, que2;
MyStack() {
}
void push(int x) {
if (que1.empty()) {
que1.push(x);
while (!que2.empty()) {
int temp = que2.front();
que2.pop();
que1.push(temp);
}
}
else {
que2.push(x);
while (!que1.empty()) {
int temp = que1.front();
que1.pop();
que2.push(temp);
}
}
}
int pop() {
int x = que1.front();
if (que1.empty()) {
x = que2.front();
que2.pop();
}
else
que1.pop();
return x;
}
int top() {
return que1.empty() ? que2.front() : que1.front();
}
bool empty() {
return que1.empty() && que2.empty();
}
};
//一个队列实现一个栈
class Stack3 {
public:
queue<int> que;
void push(int x) {
que.push(x);
for (int i = 0; i<que.size() - 1; ++i){
que.push(que.front());
que.pop();
}
}
void pop() {
que.pop();
}
int top() {
return que.front();
}
bool empty() {
return que.empty();
}
};