leetcode ---232. 用栈实现队列

链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

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

push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

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

说明:
1.你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

2.你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

3.假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

JAVA

思路

(1).入队列: 将元素放入s1中;

(2).出队列: 检测s2是否为空:
①.为空:将s1中的元素搬到s2中,删除s2中的栈顶元素,出队列。
②.非空: 直接删除s2栈顶元素,出队列。

(3).获取队列首部元素:检测s2是否为空:
①.为空:将s1中的元素搬移到s2,从s2栈顶获取。
②.非空:从s2栈顶直接获取。

(4).队列是否为空:s1、s2两个栈都为空,即队列为空。

代码如下:

class MyQueue{
      private Stack<Integer> s1;
      private Stack<Integer> 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() {
         if (s2.empty()) { //如果s2为空,就把s1中的元素全部移到s2中
            while (!s1.empty()) { //s1不为空:里面还有元素
                s2.push(s1.pop());//s1中的元素移入s2
            }
        }
        return s2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
         if (s2.empty()) {
            while (!s1.empty()) { //s1不为空:里面还有元素
                s2.push(s1.pop());//s1中的元素移入s2
            }
        }
        return s2.peek();//获取栈顶元素
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
         return s1.empty() && s2.empty();
    }
}

发布了27 篇原创文章 · 获赞 32 · 访问量 2840

猜你喜欢

转载自blog.csdn.net/m0_45097186/article/details/103961141