使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
思路:设计两个栈s1,s2,用s1模拟入队列,s2模拟出队列
队列是先进先出,栈是后进先出,所以让s1中元素出栈,入到s2中,最后栈顶就是要获取的元素(也就是队头),再把s2中元素重新放入s1中,进行下一次出入队列的实现,如图步骤1、2、3
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
void push(int x) {
s1.push(x);//把元素放入s1中
}
int pop() {
while (!s1.empty())
{
s2.push(s1.top());//从s1中获取元素,直至s1为空
s1.pop();
}
int top = s2.top();//获取s2栈顶(队列的队头)
s2.pop();//删除之后,再把s2元素放入s1中,一次就结束了
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return top;
}
/** Get the front element. */
int peek() {//只是获取,不需要做删除工作(其他与删除同理)
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int top = s2.top();
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return top;
}
bool empty() {
if (s1.empty() && s2.empty())//空则对队列的操作结束
return true;
return false;
}
stack<int> s1;
stack<int> s2;
};
使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
思路:
设计两个队列q1,q2
比如先把元素都放在了q1中,现在开始出栈(5要出去),因为队列是先进先出,就意味着放入q1的元素中只能1先出,所以就让把1、2、3、4依次移到q2中,等到q1中只剩5了,获取它,出队列。2、3等出栈同理,这样就把栈的后进先出模拟出来了
class MyStack {
public:
MyStack() {}
void push(int x) //放入元素
{
if (!q1.empty()) q1.push(x);
else q2.push(x);
}
int pop() //删除栈顶元素
{
int ret = 0;
if (!q1.empty())//不空则元素在q1中
{
while (q1.size()>1)//直到q1中剩一个,再获取,然后删除
{
q2.push(q1.front());
q1.pop();
}
ret = q1.front();//获取
q1.pop();
}
else//或者在q2中
{
while (q2.size()>1)
{
q1.push(q2.front());
q2.pop();
}
ret = q2.front();
q2.pop();
}
return ret;
}
int top() //获取栈顶元素
{
if (!q1.empty()) return q1.back();//非空直接获取队尾元素(也就相当于栈顶元素了)
else return q2.back();
}
bool empty()
{
if (q1.empty() && q2.empty())return true;
else return false;
}
queue<int> q1;
queue<int> q2;
};
若有错,欢迎指正~