前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >两个栈实现队列 && 两个队列实现栈

两个栈实现队列 && 两个队列实现栈

原创
作者头像
大学里的混子
修改2019-02-18 17:00:59
1K0
修改2019-02-18 17:00:59
举报
文章被收录于专栏:LeetCodeLeetCode

一.两个栈实现队列

代码语言:javascript
复制
public static class TwoStacksQueue {
   private Stack<Integer> stackPush;
   private Stack<Integer> stackPop;

   public TwoStacksQueue() {
      stackPush = new Stack<Integer>();
      stackPop = new Stack<Integer>();
   }

   public void push(int pushInt) {
      stackPush.push(pushInt);
   }

   public int poll() {
      if (stackPop.empty() && stackPush.empty()) {
         throw new RuntimeException("Queue is empty!");
      } else if (stackPop.empty()) {
         while (!stackPush.empty()) {
            stackPop.push(stackPush.pop());
         }
      }
      return stackPop.pop();
   }

   public int peek() {
      if (stackPop.empty() && stackPush.empty()) {
         throw new RuntimeException("Queue is empty!");
      } else if (stackPop.empty()) {
         while (!stackPush.empty()) {
            stackPop.push(stackPush.pop());
         }
      }
      return stackPop.peek();
   }
}

总结:

  1. 添加数据,直接在push栈添加
  2. poll数据,如果pop栈是空,先把push栈的数据都添加到pop栈,然后再将pop栈的栈顶数据移除,如果pop栈不是空,那么直接将pop栈的数据移除。

两个原则:

  1. 如果push的数据要往pop栈中移,一次要移完
  2. 如果pop栈中有数据,那么一定不要将push栈的数据往pop栈移动

二.两个队列实现栈

代码语言:javascript
复制
public static class TwoQueuesStack {
   private Queue<Integer> queue;
   private Queue<Integer> help;

   public TwoQueuesStack() {
      queue = new LinkedList<Integer>();
      help = new LinkedList<Integer>();
   }

   public void push(int pushInt) {
      queue.add(pushInt);
   }

   public int peek() {
      if (queue.isEmpty()) {
         throw new RuntimeException("Stack is empty!");
      }
      while (queue.size() != 1) {
         help.add(queue.poll());
      }
      int res = queue.poll();
      help.add(res);
      swap();
      return res;
   }

   public int pop() {
      if (queue.isEmpty()) {
         throw new RuntimeException("Stack is empty!");
      }
      while (queue.size() > 1) {
         help.add(queue.poll());
      }
      int res = queue.poll();
      swap();
      return res;
   }

   private void swap() {
      Queue<Integer> tmp = help;
      help = queue;
      queue = tmp;
   }

总结:

  1. 添加数据,直接在queue栈添加
  2. 移除数据,将queue栈的前n-1个元素添加到help栈,将第n个元素移除,然后修改引用。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.两个栈实现队列
  • 二.两个队列实现栈
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档