leetcode232. 用栈实现队列(java)

题目:

使用栈实现队列的下列操作:

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • empty() – 返回队列是否为空。
    leetcode232. 用栈实现队列(java)_第1张图片

示例:
leetcode232. 用栈实现队列(java)_第2张图片
代码:

  • 解法一
//思路:两个栈进行pop和peek操作
class MyQueue {
    Stack s1;
    Stack s2;
    /** Initialize your data structure here. */
    public MyQueue() {
        s1 = new Stack();
        s2 = new Stack(); 
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {	//画图很好理解 给字符串abc 经过两个栈的操作 实际存入栈中元素顺序为bottom[c b a]top
        while (!s1.empty()) s2.push(s1.pop());	//将s1栈中元素都从S1栈放到s2栈中,
        s1.push(x);	//最新进栈的元素放入s1中
        while (!s2.empty()) s1.push(s2.pop());	//再将s2栈中的元素放回s1中
        return;
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return s1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        int ret = s1.pop();	//
        s1.push(ret);
        return ret; 
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.empty(); 
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */

  • 解法二
class MyQueue {
    Stack s1, s2;
    /** Initialize your data structure here. */
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        s1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while (!s1.isEmpty()) {
            s2.push(s1.pop());	//将S1中的元素进栈到S2中
        }
        int output = s2.pop();
        while (!s2.isEmpty()) { //在恢复S1中元素
            s1.push(s2.pop());
        }
        return output;
    }

    /** Get the front element. */
    public int peek() {	//与pop()思路相同
        while (!s1.isEmpty()) {
            s2.push(s1.pop());
        }
        int output = s2.peek();
        while (!s2.isEmpty()) {
            s1.push(s2.pop());
        }
        return output;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty();
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */

你可能感兴趣的:(LeetCode刷题)