zoukankan      html  css  js  c++  java
  • 用两个栈来实现一个队列

    题目:

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

    限制:

    时间限制:1秒 空间限制:32768K 热度指数:240468

     1 package com.algorithm;
     2 
     3 import java.util.Stack;
     4 
     5 /**
     6  * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
     7  * @日期:2018年6月24日 下午9:17:49
     8  * @作者:Chendb
     9  */
    10 public class Queue {
    11 
    12     Stack<Integer> stack1 = new Stack<Integer>();
    13     Stack<Integer> stack2 = new Stack<Integer>();
    14     
    15     public static void main(String[] args) {
    16         Queue queue = new Queue();
    17         //System.out.println(queue.pop());
    18         queue.push(1);
    19         queue.push(3);
    20         
    21         System.out.println(queue.pop());
    22         queue.push(2);
    23         
    24         System.out.println(queue.pop());
    25         System.out.println(queue.pop());
    26     }
    27     
    28     public void push(int node) {
    29         stack1.push(node);
    30     }
    31     
    32     public int pop() {
    33         stack2.clear();
    34         
    35         while (!stack1.isEmpty()) {
    36             stack2.push(stack1.pop());
    37         }
    38         
    39         if (stack2.isEmpty()) {
    40             return 0;
    41         }
    42         
    43         int result = stack2.pop();
    44         
    45         while (!stack2.isEmpty()) {
    46             stack1.push(stack2.pop());
    47         }
    48         
    49         return result;
    50     }
    51     
    52 }
    View Code
  • 相关阅读:
    正则表达式
    scrollTop
    css3
    错误整理
    jquery-2
    vscode_修改字体,使用Fira Code
    实例_一个循环嵌套函数
    js_getComputed方法和style属性关于读取样式的区别
    html_html5增强的文件上传域_使用FileReader读取文件内容
    html_html5增强的文件上传域_FileList对象与File对象
  • 原文地址:https://www.cnblogs.com/cdblogs/p/9221907.html
Copyright © 2011-2022 走看看