一. 用两个栈实现队列,实现四个函数:push,pop,peek,empty
思路:
用两个栈实现队列;
一个栈s1用于入队,直接把新元素进s1,就完成了push函数。
另一个栈s2用于出队。如果s2已空,则把s1中的所有元素出栈,并push进s2,最后s2出栈,即完成队列的pop函数。
peek函数是取出队列的对首元素。
代码如下:
class MyQueue {
private:
stack<int> s1;
stack<int> s2;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x)
{
s2.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
if(s1.empty())
{
while(!s2.empty())
{
int t = s2.top();
s2.pop();
s1.push(t);
}
}
int ret = s1.top();
s1.pop();
return ret;
}
/** Get the front element. */
int peek()
{
if(s1.empty())
{
while(!s2.empty())
{
int t = s2.top();
s2.pop();
s1.push(t);
}
}
int ret = s1.top();
return ret;
}
/** Returns whether the queue is empty. */
bool empty()
{
return s1.empty() && s2.empty();
}
};
二. 用两个队列实现栈,实现四个函数:push,pop,top,empty
思路:
用两个队列q1,q2实现一个栈。push时把新元素添加到q1的队尾。
pop时把q1中除最后一个元素外逐个添加到q2中,然后pop掉q1中的最后一个元素;
这样q1的元素就为空,然后把q2的元素拷贝到q1中,也就是q1和q2交换,
保证下次操作时还是使用q1。
top的道理类似。
注意:push时始终是向q1对尾添加元素,top和pop也是对q1操作,只是q1元素全部出队后,需要把q1和q2交换。
不管top,还是pop,都需要把q1的所有元素出队,做交换前,保证q1队列为空。
算法复杂度push是O(1),pop和top都需要交换队列,复杂度是O(n)。
代码如下:
class MyStack {
private:
queue<int> q1;
queue<int> q2;
public:
/** Initialize your data structure here. */
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)
{
q2.push(q1.front());
q1.pop();
}
int a = q1.front();
q1.pop();
queue<int> tmp = q1;
q1 = q2;
q2 = tmp;
return a;
}
/** Get the top element. */
int top() {
while(q1.size() > 1)
{
q2.push(q1.front());
q1.pop();
}
int a = q1.front();
q2.push(a);
q1.pop();
queue<int> tmp = q1;
q1 = q2;
q2 = tmp;
return a;
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
};
本文介绍如何通过两个栈实现队列的功能,包括push、pop、peek和empty等核心操作;同时探讨了如何利用两个队列来模拟栈的行为,实现了push、pop、top和empty等关键函数。
388

被折叠的 条评论
为什么被折叠?



