• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: 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.

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

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

两个栈,stack1用来存push进来的元素,stack2用来存准备要pop出去的元素。push没什么好说的,pop操作时,如果stack2里面有东西,直接pop就好了,没有的话,把stack1的所有元素全存进来,再pop

 1 public class Solution {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Solution() {
 6        // do initialization if necessary
 7        stack1 = new Stack<Integer>();
 8        stack2 = new Stack<Integer>();
 9     }
10     
11     public void push(int element) {
12         stack1.push(element);
13     }
14 
15     public int pop() {
16         if (stack2.isEmpty()) {
17             while (!stack1.isEmpty()) {
18                 stack2.push(stack1.pop());
19             }
20         }
21         return stack2.pop();
22     }
23 
24     public int top() {
25         if (stack2.isEmpty()) {
26             while (!stack1.isEmpty()) {
27                 stack2.push(stack1.pop());
28             }
29         }
30         return stack2.peek();
31     }
32 }

 

posted @ 2015-02-07 07:51  neverlandly  阅读(444)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3