剑指Offer-用两个栈实现队列

66 阅读2分钟

题目

请用栈实现一个队列,支持如下四种操作:

  • push(x) – 将元素x插到队尾;
  • pop() – 将队首的元素弹出,并返回该元素;
  • peek() – 返回队首元素;
  • empty() – 返回队列是否为空;

注意:

  • 你只能使用栈的标准操作:push to toppeek/pop from topsize 和 is empty
  • 如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
  • 输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;

数据范围

每组数据操作命令数量 [0,100][0,100]。

样例

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

解析

push(): 向stk1添加元素即可;
pop(): 如果stk2非空,将stk2栈顶元素弹出并返回即可;若stk2为空,就将stk1所有元素加到stk2;
peek():如果stk2非空,将stk2栈顶元素返回即可;若stk2为空,就将stk1所有元素加到stk2;
empty(): 若stk1和stk2都为空,返回true;否则返回false。

代码

C++

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> stk1;
    stack<int> stk2;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stk1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (stk2.empty()) {
            while (!stk1.empty()) {
                stk2.push(stk1.top());
                stk1.pop();
            }
        }
        
        auto t = stk2.top();
        stk2.pop();
        return t;
    }
    
    /** Get the front element. */
    int peek() {
        if (stk2.empty()) {
            while (!stk1.empty()) {
                stk2.push(stk1.top());
                stk1.pop();
            }
        }
        
        return stk2.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stk1.empty() && stk2.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

Python

class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stk1 = []
        self.stk2 = []
        

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.stk1.append(x)
        

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if not self.stk2:
            while self.stk1:
                self.stk2.append(self.stk1.pop())
        return self.stk2.pop()

                

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        if not self.stk2:
            while self.stk1:
                self.stk2.append(self.stk1.pop())
        return self.stk2[-1]
        

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return not self.stk1 and not self.stk2
        


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

GO

type MyQueue struct {
    s1 []int
    s2 []int
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{}
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    this.s1 = append(this.s1, x)
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    if len(this.s2) == 0 {
        for len(this.s1) > 0{
            this.s2 = append(this.s2, this.s1[len(this.s1) - 1])
            this.s1 = this.s1[:len(this.s1) - 1]
        }
    }
    ans := this.s2[len(this.s2) - 1]
    this.s2 = this.s2[:len(this.s2) - 1]
    return ans
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    if len(this.s2) == 0 {
        for len(this.s1) > 0{
            this.s2 = append(this.s2, this.s1[len(this.s1) - 1])
            this.s1 = this.s1[:len(this.s1) - 1]
        }
    }
    ans := this.s2[len(this.s2) - 1]
    return ans
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
    return len(this.s1) == 0 && len(this.s2) == 0
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */