• 剑指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 }
  • 相关阅读:
    C语言扩展题
    C语言第五题
    C语言第四题
    C语言第三题
    c语言第二题
    11
    游戏开发的一些想法
    openxml的视频教程
    JavaScript调试之console.log
    IPPatternConverter
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11168272.html
Copyright © 2020-2023  润新知