zoukankan      html  css  js  c++  java
  • 剑指Offer——用两个栈实现队列

    1、题目描述

      用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    2、代码实现

     1 package com.baozi.offer;
     2 
     3 import java.util.Stack;
     4 
     5 /**
     6  * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
     7  *
     8  * @author BaoZi
     9  * @create 2019-07-11-9:47
    10  */
    11 public class Offer5 {
    12     Stack<Integer> stack1 = new Stack<Integer>();
    13     Stack<Integer> stack2 = new Stack<Integer>();
    14 
    15     //1、实现队列的push操作
    16     public void push(int node) {
    17         stack1.push(node);
    18     }
    19 
    20     //2、实现队列的pop操作
    21 
    22     /**
    23      * 通过两个栈实现一个队列的输出操作思路就是:根据栈数据结构的特点,先把非空的栈stack1中的元素全部转移到另外一个
    24      * 空栈stack2中,此时stack2的栈顶元素就是第一个存入栈中的元素,保存在一个临时变量中输出即可,在然后在stack2中的
    25      * 元素再一次全部转移到stack1中。
    26      * 每次操作都经过这样几个步骤就能模拟实现出队列的效果。
    27      *
    28      * @return
    29      */
    30     public int pop() {
    31         while (!stack1.isEmpty()) {
    32             stack2.push(stack1.pop());
    33         }
    34         int first = stack2.pop();
    35         while (!stack2.isEmpty()) {
    36             stack1.push(stack2.pop());
    37         }
    38         return first;
    39     }
    40 }
  • 相关阅读:
    Struts2(二)
    jiqixuexi
    UTF-8
    mysql load
    linux命令(转)
    apache FTP站点源码下载
    linux 命令
    clickhouse 查询
    CDH learning
    nfs
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11168272.html
Copyright © 2011-2022 走看看