zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks

    一、题目

      1、审题

      

      2、分析

        使用栈来实现队列的功能。

    二、解答

      1、思路

        方法一、

          只修改 Pop 方法,使得栈中元素排序为队列的规则。

     1 public class MyQueue {
     2     
     3     Stack<Integer> stack;
     4     /** Initialize your data structure here. */
     5     public MyQueue() {
     6         stack = new Stack<>();
     7     }
     8     
     9     /** Push element x to the back of queue. */
    10     public void push(int x) {
    11         if(stack.isEmpty()) {
    12             stack.push(x);
    13         }
    14         else {
    15             Stack<Integer> tmp = new Stack<>();
    16             while(!stack.isEmpty())
    17                 tmp.push(stack.pop());
    18             stack.push(x);
    19             while(!tmp.isEmpty())
    20                 stack.push(tmp.pop());
    21         }
    22     }
    23     
    24     /** Removes the element from in front of queue and returns that element. */
    25     public int pop() {
    26         return stack.pop();
    27     }
    28     
    29     /** Get the front element. */
    30     public int peek() {
    31         return stack.peek();
    32     }
    33     
    34     /** Returns whether the queue is empty. */
    35     public boolean empty() {
    36         return stack.isEmpty();
    37     }
    38 }

      方法二、

        使用两个 Stack,input、output。

        push: 压入 input 栈。

        pop、peek: 若 output 不为空,则对 output 操作; 若 output 为空,则将 input 元素全部压入 output,在对 output 操作。

        empty: 当 output、input 全为空时才返回 true。

     1 class MyQueue {
     2 
     3     Stack<Integer> input = new Stack<>();
     4     Stack<Integer> output = new Stack<>();
     5     
     6     public void push(int x) {
     7         input.push(x);
     8     }
     9     
    10     public int pop() {
    11         peek();
    12         return output.pop();
    13     }
    14     
    15     public int peek() {
    16         if(output.isEmpty()) {
    17             while(!input.isEmpty())
    18                 output.push(input.pop());
    19         }
    20         return output.peek();
    21     }
    22     
    23     public boolean empty() {
    24         return input.empty() && output.empty();
    25     }
    26 }

        

  • 相关阅读:
    Codeforces 765 E. Tree Folding
    Codeforces 617 E. XOR and Favorite Number
    2017.3.4[hihocoder#1403]后缀数组一·重复旋律
    2017.2.23[hdu1814]Peaceful Commission(2-SAT)
    2017.2.18Codeforces Round #398 (Div. 2)
    2017.2.18[codevs1170]NOIP2008提高组复赛T4双栈排序
    2017.2.18[codevs3319][bzoj3670]NOI2014D2T1动物园
    2017.2.18[codevs3311][bzoj3668]NOI2014D1T1起床困难综合症
    2017.2.10 Splay总结
    2017.2.10考试总结2017冬令营
  • 原文地址:https://www.cnblogs.com/skillking/p/9930483.html
Copyright © 2011-2022 走看看