用队列实现栈

作者: 飞白非白 | 来源:发表于2018-12-04 23:33 被阅读5次

/**
Description

Implement the following operations of a stack using queues.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty

*/
class MyStack {
    /** Initialize your data structure here. */
    private LinkedList<Integer> q1 = new LinkedList<>();
    public MyStack() {
        q1 = new LinkedList<Integer>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        q1.add(x);
        int size = q1.size();
        while(size > 1){
            q1.add(q1.remove());
            size--;
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q1.remove();
    }

    /** Get the top element. */
    public int top() {
        return q1.peek();
    }

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

相关文章

  • 数据结构——栈和队列

    用数组实现栈和队列 用栈实现队列 用队列实现栈 栈和队列的经典算法题最小间距栈宠物收养所 数组实现栈和队列 用数组...

  • leecode刷题(26)-- 用栈实现队列

    leecode刷题(26)-- 用栈实现队列 用栈实现队列 使用栈实现队列的下列操作: push(x) -- 将一...

  • C语言第七次作业:链表

    707. 设计链表 空指针 空节点 225. 用队列实现栈 链式存储栈 双队列实现栈 232. 用栈实现队列 链式...

  • 队列之-队列实现栈

    一、队列实现栈核心算法概述 之前已经描述过了用栈实现队列的功能,见栈系列之-实现队列,那么同样队列也可以用来实现栈...

  • 38_两个有趣的问题

    关键词:通过栈实现队列、通过队列实现栈 0. 通过栈实现队列 用栈实现队列等价于用后进先出的特性实现先进先出的特性...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

  • LeetCode 每日一题 [12] 用队列实现栈

    LeetCode 用队列实现栈 [简单] 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈pop(...

  • Python学习教程:用队列实现栈

    接着上一期跟大家说的用栈实现队列,这期的Python学习教程跟大家讲用队列实现栈 题目:使用队列实现栈的下列操作:...

  • 用两个栈实现队列,用两个队列实现堆栈

    参考:剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈 用两个栈实现队列stack1作为入...

网友评论

    本文标题:用队列实现栈

    本文链接:https://www.haomeiwen.com/subject/wfubcqtx.html