面试题 03.04. Implement Queue using Stacks LCCI

Problem

Implement a MyQueue class which implements a queue using two stacks.

Notes:

  • You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Example

MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // return 1
queue.pop(); // return 1
queue.empty(); // return false

Solution

栈s1用于push,s2用于peek和pop。
peek和pop的返回值都来自s2:

  • 当s2中有元素时,直接返回栈顶元素;
  • 当s2中没有元素值,就将s1中的元素全部弹出,并压入s2,然后返回栈顶元素
class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        while(!s1.empty())
        {
            s1.pop();
        }

        while(!s2.empty())
        {
            s2.pop();
        }

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(!s2.empty())
        {
            int tmp = s2.top();
            s2.pop();
            return tmp;
        }
        else
        {
            while(!s1.empty())
            {
                int tmp = s1.top();
                s1.pop();
                s2.push(tmp);
            }

            int tmp = s2.top();
            s2.pop();
            return tmp;
        }
        

    }
    
    /** Get the front element. */
    int peek() {
        if(!s2.empty())
        {
            return s2.top();
        }
        else
        {
            while(!s1.empty())
            {
                int tmp = s1.top();
                s1.pop();
                s2.push(tmp);
            }

            return s2.top();
        }

    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s1.empty() && s2.empty();

    }

    stack<int> s1;
    stack<int> s2;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105060788