博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode第225题:Implement Stacks using Queues
阅读量:4494 次
发布时间:2019-06-08

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

Problem

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).

题目

使用队列实现栈的如下操作。

  • push(x)——把元素x到堆栈。
  • pop()——删除元素堆栈的顶部。
  • top()——获得顶级元素。
  • empty()——返回栈是否为空。

注意

  • 必须只使用队列的标准操作——这意味着只有下面操作是有效的:push队尾,peek/pop对首,size(),是否为空。
  • 根据所用编程语言,只要你只使用队列的标准操作,即使本机不支持队列,也可以通过链表或者双端队列来模拟。
  • 假设所有的操作是有效的(比如空栈中没有pop和top操作)。

题解

解题思路

题目的要求是使用队列来实现栈 ,有两种思路可以解决

  • 一种是使用队首作为栈顶
  • 一种是使用队尾作为栈顶

两种思路应该都可以实现,一种是入栈操作会多一些,一种是出栈操作会多一些。这个题目四个函数中两个都是和栈顶元素的操作有关,因此选择用队首作为栈顶。

代码

/** * 使用队列来实现栈。 * 

使用队列的队首来当做栈顶。 * @author zhao * * @param

*/public class _225_Implement_Stacks_using_Queues {
Queue
q = new LinkedList
(); // Push element x onto stack. public void push(int x) { q.add(x); int n = q.size(); while (n > 1) { n--; q.add(q.poll()); } } // Removes the element on top of the stack. public void pop() { q.poll(); } // Get the top element. public int top() { return q.peek(); } // Return whether the stack is empty. public boolean empty() { return q.isEmpty(); } }

转载于:https://www.cnblogs.com/dantezhao/p/5365157.html

你可能感兴趣的文章
LeetCode58 Length of Last Word
查看>>
Python基础语法 系统学习
查看>>
ios开发之数据的持久化存储机制
查看>>
poj 3264
查看>>
图标跟着摄像机(Camera)orthographicSize的值改变大小
查看>>
LeetCode 386——字典序排数
查看>>
linux如何挂载windows下的共享文件
查看>>
常用正则表达式
查看>>
Houdini 节点参数读取输入节点的数据列表
查看>>
初识Linq to Entity
查看>>
Linux vmstat命令实战详解
查看>>
FastDFS在centos上的安装配置与使用
查看>>
HDU 1709 The Balance
查看>>
2016/7/7 设置wamp2.5 mysql密码 重点是mysql版本
查看>>
简介几种负载均衡原理
查看>>
micropython logging文档
查看>>
Webform(分页、组合查询)
查看>>
Foundation - NSDate
查看>>
geatpy - 遗传和进化算法相关算子的库函数(python)
查看>>
iOS 线程安全
查看>>