232.用栈实现队列
题目链接:用栈实现队列
视频讲解:栈的基本操作
主要考察的是对栈和队列的熟练程度。
class MyQueue {
public:
stack<int> sIn;
stack<int> sOut;
MyQueue() {
}
void push(int x) {
sIn.push(x);
}
int pop() {
if (sOut.empty())
{
while (!sIn.empty())
{
sOut.push(sIn.top());
sIn.pop();
}
}
int res = sOut.top();
sOut.pop();
return res;
}
int peek() {
int res = this->pop();
sOut.push(res);
return res;
}
bool empty() {
return (sOut.empty() && sIn.empty());
}
};
225. 用队列实现栈
题目链接:用队列实现栈
视频讲解:队列的基本操作
题目叙述,用两个队列实现栈,其实可以更简单一点,用一个队列实现栈。一个队列中,要达到出栈的效果,只需把队头出来的元素放到队尾,弹出原来队列的最后一个元素即可。
两个队列
class MyStack {
public:
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size();
size--;
while (size--) // 把q1放到q2中,留下最后一个
{
q2.push(q1.front()); // 先往q2放
q1.pop(); // 再从q1弹出
}
int res = q1.front();
q1.pop();
q1 = q2; // q2赋给q1
while (!q2.empty()) // 清空q2
{
q2.pop();
}
return res;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};
一个队列
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
size--;
while (size--)
{
q.push(q.front());
q.pop();
}
int res = q.front();
q.pop();
return res;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
};