leetcode225和232 用两个队列实现栈和用两个队列实现栈
这两道题目的思想是一样的都要完成两次拷贝,当要进行弹出值的时候都先把输入栈(输入队列)中的元素拷贝到缓存栈(缓存队列)中然后进行弹出操作,之后将缓存栈(缓存队里)中元素全部拷贝输入栈(输入队列)
leetcode 232用两个栈实现队列
核心思想:1、定义两个栈输入栈,输出栈,每次都把一个栈中的全部元素倒入另一个栈中
输入队列维持输入,输出队列进行输出操作
2、当两个栈都为空的时候实现的队列才为空,否则为ture
leetcode AC代码如下
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> instack,outstack;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
if(outstack.empty())
{
instack.push(x);
}
else
{
while(!outstack.empty())
{
instack.push(outstack.top());
outstack.pop();
}
instack.push(x);
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!instack.empty())
{
outstack.push(instack.top());
instack.pop();
}
int n=outstack.top();
outstack.pop();
return n;
}
/** Get the front element. */
int peek() {
while(!instack.empty())
{
outstack.push(instack.top());
instack.pop();
}
int n=outstack.top();
return n;
}
/** Returns whether the queue is empty. */
bool empty() {
return outstack.empty()&&instack.empty();
}
};
leetcode 225
核心思想 维护一个输入队列和输出队列
要进行两次拷贝
第一把输入队列里的值依次拷贝到输出队列里直到最后一个然后进行top(),pop()取值操作
同时要进行第二次拷贝要把输出队列里全部元素拷回到输入队列里
2、当两个栈都为空的时候实现的队列才为空,否则为ture
思路
入栈
将元素 x 直接放入 q1 队列中。
出栈
也就是把 q1 的队尾元素出队列,由于队列只能从队头出队,因此先把 q1 中除了队尾元素的其他值存到 q2 中
再把队尾元素也就是栈顶出队
最后将 q2 中的值存到 q1 中
获取栈顶元素
也就是获取 q1 的队尾元素
leetcode AC代码
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q1,q2;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while(q1.size()>1)
{
int n=q1.front();
q1.pop();
q2.push(n);
}
int n=q1.front();
q1.pop();
if(q1.empty())
{
while(!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
}
return n;
}
/** Get the top element. */
int top() {
while(q1.size()>1)
{
int n=q1.front();
q1.pop();
q2.push(n);
}
int n=q1.front();
q2.push(n);
q1.pop();
if(q1.empty())
{
while(!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
}
return n;
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty()&&q2.empty();
}
};