Implement Queue by Stacks

原题链接 : http://lintcode.com/zh-cn/problem/implement-queue-by-stacks/#

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

样例

For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2

挑战

implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

SOLUTION 1:

使用两个栈,stack1和stack2。

http://www.ninechapter.com/problem/49/

对于Queue的操作对应如下:
Queue.Push:
    push到Stack1
 
Queue.Pop:
    如果Stack2非空,Stack2.pop
    否则将Stack1中的所有数pop到Stack2中(相当于顺序颠倒了放入),然后Stack2.pop()
 
每个数进出Stack1和Stack2各1次,所以两个操作的均摊复杂度均为O(1)
 public class Solution {
private Stack<Integer> stack1;
private Stack<Integer> stack2; public Solution() {
// do initialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
} public void push(int element) {
// write your code here
stack1.push(element);
} public int pop() {
// write your code here
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
} return stack2.pop();
} public int top() {
// write your code here
// write your code here
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
} return stack2.peek();
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/stack/StackQueue.java

最新文章

  1. Android组件安全
  2. maven记录
  3. 关于 c# 操作 world
  4. 13Spring_AOP编程(AspectJ)_后置通知
  5. yii中sphinx索引配置解析
  6. loutsScript 常用代码
  7. 网站压力测试工具-Webbench源码笔记
  8. Redis系列整理
  9. CST 公共生成树
  10. CorelDraw X8 破解激活问题
  11. CRM实施失败?请注意这6大问题及对策!
  12. 软件测试实验四----mujava变异测试
  13. eclipse中js报错简单快捷的解决方式
  14. js 一些兼容检测
  15. php 无法正确获取系统当前时间的解决办法
  16. (3)The critical role librarians play in the opioid crisis
  17. [2016北京集训测试赛15]statement-[线段树+拆环]
  18. pandas入门——loc与iloc函数
  19. 我的Oracle控制台创建数据库的工具
  20. tomcat源码阅读之Server和Service接口解析

热门文章

  1. memcached内存管理机制[未整理]
  2. 树莓派进阶之路 (010) - 树莓派raspi-config配置(转)
  3. linux 文件系统工作原理
  4. 【jsp】Servlet与jsp之间的传值
  5. 基于matplotlib的数据可视化(图形填充fill fill_between) - 笔记(二)
  6. cucumber java从入门到精通(2)用代码定义步骤
  7. 使用base64编码的好处
  8. Android调用系统软键盘
  9. axios 简单常用笔记
  10. jenkins 批量修改 去掉勾选Build whenever a SNAPSHOT dependency is built