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 }

        

  • 相关阅读:
    定制化培养:破解企业人才之困
    IT毕业生需要具备的六种能力素质
    JAVA值传递or引用传递
    就业形势严峻 毕业生需练好“内功”
    如何改变mysql auto increment 步长和初始值
    python变量作用域
    关于python的lxml.html 的fromstring 函数
    python string 到date object
    python mysql 连接数据库 latin1 codec错误
    python 使用 mysqldb 批量插入数据
  • 原文地址:https://www.cnblogs.com/skillking/p/9930483.html
Copyright © 2011-2022 走看看