容器的pop方法不会返回弹出的值
思路:
双栈模拟队列队尾进队头出(先进先出):入队时把元素在输入栈直接入栈,则输入栈的top即队尾;出队把输出栈的top元素弹出,当输出栈为空时,则应当弹出输入栈的栈底元素(即先将输入栈依次弹出压入输出栈,再将输出栈的top元素弹出)。
class MyQueue {
public:
stack<int> inS, outS;
MyQueue() {
}
void push(int x) {
inS.push(x);
}
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (outS.empty()) {
// 从stIn导入数据直到stIn为空
while(!inS.empty()) {
outS.push(inS.top());
inS.pop();
}
}
int top = outS.top();
outS.pop();
return top;
}
int peek() {
int top = pop();//在连续pop后outS可能为空,所以不能直接返回outS.top()作为队头元素
outS.push(top);
return outS.top();
}
bool empty() {
return inS.empty() && outS.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();
*/
思路:
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序。
class MyStack {
public:
queue<int> qS;
MyStack() {
}
void push(int x) {
qS.push(x);
}
int pop() {
for(int i = 0; i < qS.size()-1;i++){
int temp = qS.front();
qS.pop();
qS.push(temp);
}
int result = qS.front();
qS.pop();
return result;
}
int top() {
return qS.back();
}
bool empty() {
return qS.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();
*/