leetcode第225题:Implement Stacks using Queues
2015-07-26 17:38
369 查看
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操作)。
题解
解题思路
题目的要求是使用队列来实现栈 ,有两种思路可以解决一种是使用队首作为栈顶
一种是使用队尾作为栈顶
两种思路应该都可以实现,一种是入栈操作会多一些,一种是出栈操作会多一些。这个题目四个函数中两个都是和栈顶元素的操作有关,因此选择用队首作为栈顶。
代码
/** * 使用队列来实现栈。 * <p>使用队列的队首来当做栈顶。 * @author zhao * * @param <E> */ public class _225_Implement_Stacks_using_Queues { Queue<Integer> q = new LinkedList<Integer>(); // 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(); } }
相关文章推荐
- easyui searchbox
- UESTC 250 windy数(数位DP)
- UITextField限制文本长度 , UI控件 自适应宽高 。
- ZOJ - 2548 Prerequisites?
- 用Fluentd实现收集日志到HDFS(上)
- [iOS]类似新浪微博或者人人客户端中,中间UITabBarItem只有图片,使图片居中的方法
- HDU 5312 Sequence
- Tair-淘宝自主开发的一个分布式key/value存储系统
- Number Guessing
- 6.1.Virtio 原理与Guest OS driver
- Workqueue机制的实现
- UIImage+ImageEffects
- 树莓派与arduino串行通信
- Can Live View boot up images acquired from 64bit OS evidence?
- HDOJ_Problem Archive_1005_Number Sequence
- Leetcode(62)(63) Unique Paths I II
- iOS中自定义UIImageView用TargetAction模式实现关灯小游戏
- U盘安装Ubuntu15.04 出现boot failed: please change disks and press a key to continue 错误
- Building an MFC project for a non-Unicode character set is deprecated
- MapReduce的KeyValueTextInputFormat