LeetCode 232.用栈实现队列
题目链接:232.用栈实现队列
踩坑:对于STL中stack的成员函数还不熟悉,比如应该是empty不是is_empty,是top不是peek,pop没有返回值
思路:两个栈相互捯饬,用一个栈来维持队列的形态,另一个用来将栈反转(栈顶变栈底)
代码:
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
s.push(x);
}
int pop() {
while(!s.empty())
{
int a = s.top();
t.push(a);
s.pop();
}
int top = t.top();
t.pop();
while(!t.empty())
{
int a = t.top();
s.push(a);
t.pop();
}
return top;
}
int peek() {
while(!s.empty())
{
int a = s.top();
t.push(a);
s.pop();
}
int top = t.top();
while(!t.empty())
{
int a = t.top();
s.push(a);
t.pop();
}
return top;
}
bool empty() {
return s.empty();
}
private:
stack<int> t;
stack<int> s;
};
/**
* 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();
*/
LeetCode 225.用队列实现栈
题目链接:225.用队列实现栈
踩坑:队列里不是peek是front,还可以有back
思路:一个队列就可以完成对栈的模拟。将队头push到队尾即可(记得pop)
代码:
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int count = 0;
while(count < q.size()-1)
{
q.push(q.front());
q.pop();
count++;
}
int top = q.front();
q.pop();
return top;
}
int top() {
int count = 0;
while(count < q.size()-1)
{
q.push(q.front());
q.pop();
count++;
}
int top = q.front();
q.push(top);
q.pop();
return top;
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
/**
* 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();
*/