原题网址:https://www.lintcode.com/zh-cn/old/problem/implement-queue-by-two-stacks/#
40. 用栈实现队列
讨论区
正如标题所述,你需要使用两个栈来实现队列的一些操作。
队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。
pop和top方法都应该返回第一个元素的值。
样例
比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2
挑战
仅使用两个栈来实现它,不使用任何其他数据结构,push,pop 和 top的复杂度都应该是均摊O(1)的
标签
挑战的要求是不使用任何其他数据结构,这里不清楚使用int 型变量保存头结点数值是否属于使用其他数据结构?
以及push,pop 和 top的复杂度都应该是均摊O(1)的,啥叫均摊……?一脸懵逼 =_=
我自己的思路:创建一个int型数据成员first保存头结点数值,再创建一个stack<int>型的 m_s 保存队列数据;
1 push元素时,判断 m_s 是否为空,为空则first=element,不为空保持原来的值不变;
2 top就直接return first;
3 pop,先创建临时变量保存first,最后要return出去。然后定义一个stack<int>型的中间变量temp,将m_s中的值倒着压入temp中,弹出temp尾部元素(即队列顶部元素),此时temp的新尾部即为队列的新头结点,将其赋值给frist。然后将temp中的元素再倒着压入m_s中,队列更新完毕。【注意:对stack型变量top或者pop时要先进行判空!本题的条件pop可以不判断,但top不加判空的话,若队列只有一个元素,pop后再top程序出错,哎……第一次运行时就这么栽了,还排查了半天,蠢哭】
AC代码:
class MyQueue {
public:
MyQueue() {
// do intialization if necessary
}
/*
* @param element: An integer
* @return: nothing
*/
void push(int element) {
// write your code here
if (m_s.empty())
{
First=element;
}
m_s.push(element);
}
/*
* @return: An integer
*/
int pop() {
// write your code here
int result=First;
stack<int> temp;
while(!m_s.empty())
{
temp.push(m_s.top());
m_s.pop();
}
temp.pop();//犯蠢了,如果temp弹出栈顶元素后为空,top操作会出错;
if (!temp.empty())//所以这里一定要加判空;
{
First=temp.top();
}
while(!temp.empty())
{
m_s.push(temp.top());
temp.pop();
}
return result;
}
/*
* @return: An integer
*/
int top() {
// write your code here
return First;
}
int First; //存储队列头;
stack<int> m_s;//存储元素;
};
其他方法:
https://blog.csdn.net/ljlstart/article/details/48517213
每次上网一搜索其他思路就会感慨大神何其多,自己还差得远呢。
设置两个栈,入队列的元素存放在s1中,出队列时元素都从s2中出。
push时直接把元素加到s1中;
pop时保存s2尾部数据以便最后return出去,然后弹出该元素。这里首先要先判断s2是否为空,若为空,将s1中元素倒着插入到s2中(这样s1是空栈,push时不影响);
top同理pop,只是少了一部弹出元素的操作。
AC代码:
class MyQueue {
public:
MyQueue() {
// do intialization if necessary
}
void push(int element) {
// write your code here
s1.push(element);
}
int pop() {
// write your code here
if (s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
int r=s2.top();
s2.pop();
return r;
}
int top() {
// write your code here
if (s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
stack<int> s1;//存放入队元素;
stack<int> s2;//元素从这里弹出;
};
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步