232 Implement Queue using Stacks
class MyQueue {
public:
stack<int> stkIn;
stack<int> stkOut;
MyQueue() {
}
void push(int x) {
stkIn.push(x);
}
int pop() {
if(stkOut.empty()){
while(!stkIn.empty()){
stkOut.push(stkIn.top());
stkIn.pop();
}
}
int res = stkOut.top();
stkOut.pop();
return res;
}
int peek() {
int res = this->pop();
stkOut.push(res);
return res;
}
bool empty() {
return stkIn.empty() && stkOut.empty();
}
};
注意:
1.思路,用两个栈
2.pop的时候要注意判断stkOut是不是空
225. Implement Stack using Queues
1.两个queue
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size();
size--;
while(size--){
que2.push(que1.front());
que1.pop();
}
int res = que1.front();
que1.pop();
que1 = que2;
while(!que2.empty()){
que2.pop();
}
return res;
}
int top() {
return que1.back();
}
bool empty() {
return que1.empty();
}
};
其中一个queue只是单纯用来记录最后一个值
可以只用一个队列
int pop() {
int size = que1.size();
size--;
while(size--){
que1.push(que1.front());
que1.pop();
}
int res = que1.front();
que1.pop();
return res;
}