博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Implement Stack Using Queues
阅读量:4551 次
发布时间:2019-06-08

本文共 1467 字,大约阅读时间需要 4 分钟。

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.

Notes:

  • You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Update (2015-06-11):

The class name of the Java function had been updated to MyStack instead of Stack.

Credits:

Special thanks to for adding this problem and all test cases.

 Solution:
O(1)
class MyStack {    private Queue queue;        // Push element x onto stack.    public void push(int x) {        Queue q = new LinkedList();        q.add(x);        q.add(queue);        queue = q;                }    // Removes the element on top of the stack.    public void pop() {        queue.remove();        queue = (Queue) queue.peek();    }    // Get the top element.    public int top() {        return (int)queue.peek();    }    // Return whether the stack is empty.    public boolean empty() {        return queue==null;    }}

 

 
 
 
 
 

转载于:https://www.cnblogs.com/lishiblog/p/5870428.html

你可能感兴趣的文章
匿名方法和Lambda表达式
查看>>
Spark编译的三种方式
查看>>
京东的核心业务
查看>>
读书笔记(六)--成交
查看>>
Secret Number hdu 2113
查看>>
软件架构(体系结构,Architecture)和软件框架
查看>>
阶梯博弈(没怎么搞懂)
查看>>
python request post请求body中有json数组
查看>>
IDT hook KiTrap03
查看>>
字节对齐
查看>>
使用Python SocketServer快速实现多线程网络服务器
查看>>
离散数学
查看>>
外观模式理解和示例
查看>>
IDEA远程仓库版本回滚
查看>>
C++矩阵库 Eigen 简介(转载)
查看>>
sklearn的train_test_split()各函数参数含义解释(非常全)
查看>>
机器学习算法的整体流程(非常易懂)
查看>>
机器学习梯度下降法的数学原理(非常易懂)
查看>>
数据归一化Scaler-机器学习算法
查看>>
机器学习线性回归算法的评价指标(简单线性回归问题)
查看>>