232.用栈实现队列
链接: 232.用栈实现队列
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
int tmp = 0;
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
tmp = s2.top();
s2.pop();
return tmp;
}
int peek() {
int tmp = this->pop();
s2.push(tmp);
return tmp;
}
bool empty() {
return s1.empty() && s2.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();
*/
思路与收获
- 本题思路比较简单,只要对栈与队列的特性稍有了解就能理解,只不过在代码实现时尤其是在实现队列的pop操作时,如果出栈为空,则要把入栈的数据全部移送过来,只要出栈不为空,则继续pop出栈的元素,这一点在写代码时可能不会想到,导致代码实现复杂。
225.用队列实现栈
链接: 225.用队列实现栈
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int result = 0;
for(int i = 0; i < q.size() - 1; ++i)
{
q.push(q.front());
q.pop();
}
result = q.front();
q.pop();
return result;
}
int top() {
return q.back();
}
bool empty() {
return q.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();
*/
思路与收获
- 本题稍微不太容易想到的地方就是如何只用一个队列模拟栈的功能,想明白队列可以循环就可以成功模拟栈的功能。