【一次过】Lintcode 40. 用栈实现队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/81635460

正如标题所述,你需要使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。

样例

比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2

挑战

仅使用两个栈来实现它,不使用任何其他数据结构,push,pop 和 top的复杂度都应该是均摊O(1)的


解题思路:

使用两个栈,一个栈s当作push()后存放的地方,如果需要pop或者top操作,则用临时的一个栈tmp,将已经倒放元素的栈s中的元素依次放进tmp中,相当于再次倒放,负负得正,此时元素就为正置,就能按照队列的操作执行,执行完毕后再依次将元素从tmp倒放回s中,保持栈应有的性质。

class MyQueue {
public:
    MyQueue() 
    {
        // do intialization if necessary
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    void push(int element) 
    {
        // write your code here
        s.push(element);
    }

    /*
     * @return: An integer
     */
    int pop() 
    {
        // write your code here
        stack<int> tmp;
        
        while(!s.empty())
        {
            tmp.push(s.top());
            s.pop();
        }
        
        int res = tmp.top();
        tmp.pop();
        
        while(!tmp.empty())
        {
            s.push(tmp.top());
            tmp.pop();
        }
        
        return res;
    }

    /*
     * @return: An integer
     */
    int top() 
    {
        // write your code here
        stack<int> tmp;
        
        while(!s.empty())
        {
            tmp.push(s.top());
            s.pop();
        }
        
        int res = tmp.top();
        
        while(!tmp.empty())
        {
            s.push(tmp.top());
            tmp.pop();
        }
        
        return res;
    }
    
private:
    stack<int> s;
};

JAVA代码:

思想与上面的稍有不同,因为上面的做法,每次pop(),peek()都要来回交换两次,比较费时间。现在的思路是一个栈用来push,一个栈用来pop,压数据只压入stackPush栈中,取数据只用stackPop栈。具体两个栈是如何联动的?当stackPop栈不为空时,直接pop或peek即可,否则stackPop栈为空,需要从stackPush中翻转传送数据过来,将stackPush中所有数据弹出再压入stackPop栈即可。由于每次都是stackPop栈为空时再全部压栈,所以数据依然保持队列特性,而且不用向上面方法来回倒腾。

public class MyQueue {
    Stack<Integer> stackPush;
    Stack<Integer> stackPop;
    
    public MyQueue() {
        // do intialization if necessary
        stackPush = new Stack<>();
        stackPop = new Stack<>();
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
        stackPush.push(element);
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
        if(stackPop.empty()){
            while(!stackPush.empty())
                stackPop.push(stackPush.pop());
        }
        
        return stackPop.pop();
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        if(stackPop.empty()){
            while(!stackPush.empty())
                stackPop.push(stackPush.pop());
        }
        
        return stackPop.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/81635460
今日推荐