40 用栈实现队列

原题网址: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;//存储元素;
};
 
 

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9069701.html
40