欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode_225. 用队列实现栈

程序员文章站 2023-12-28 12:00:40
...
class MyStack {
    // 创建队列对象
    Queue<Integer> q = new LinkedList<Integer>();
    // 初始化结构体
    public MyStack() {
    }
    // 传入元素入栈
    public void push(int x) {
        // 添加一个元素并返回true(如果队列已满,则返回false)
        q.offer(x);
    }

   // 删除栈顶的元素
    public int pop() {
        int s = q.size();
        int p;
        for(int i = 0; i<s-1; i++){
            // 移除并返问队列头部的元素(如果队列为空,则返回null)
            p = q.poll();
            q.offer(p);
        }
        // 返回移除的元素
        return q.poll();
    }

    // 获得栈顶元素
    public int top() {
        int s = q.size();
        int p = 0;
        for(int i = 0; i<s; i++){
            p = q.poll();
            q.offer(p);
        }
        return p;
    }

    // 判断是否为空
    public boolean empty() {
        return q.size() == 0;
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

 

上一篇:

下一篇: