思路:
1.建立两个栈,一个入栈stIn,一个出栈stOut
2.往队列里push元素,等价于往入栈里push;队列pop元素时,如果出栈为空,把入栈里的元素依次pop,再push进出栈里,最后pop栈顶元素
代码:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int result = this->pop();
stOut.push(result);
return result;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
思路:
1.push:建立一个队列que实现栈,当往栈里push元素时,等价于往队列里push
2.pop:由于pop的元素位于队列里的最后一个,所以先统计队列的size,将最后一个元素的前面size-1个元素依次加入到队尾,相当于que.push(que.front()),最后再pop
代码:
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
while(size--){
que.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
return res;
}
int top() {
return que.back();
}
bool empty() {
return que.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();
*/