• 用两个栈实现一个队列


    【题目】两个栈实现一个队列

     1 import java.util.Stack;
     2 
     3 public class Main {
     4 
     5     public static void main(String[] args) {
     6 
     7         Stack<Integer> stack1 = new Stack<Integer>();
     8         Stack<Integer> stack2 = new Stack<Integer>();
     9 
    10         MyQueue myQueue = new MyQueue(stack1, stack2);
    11 
    12         myQueue.appendTail(1);
    13         myQueue.appendTail(2);
    14         myQueue.appendTail(3);
    15         System.out.println(myQueue.deleteHead());
    16         System.out.println(myQueue.deleteHead());
    17         myQueue.appendTail(4);
    18         myQueue.appendTail(5);
    19         System.out.println(myQueue.deleteHead());
    20         System.out.println(myQueue.deleteHead());
    21         System.out.println(myQueue.deleteHead());
    22         System.out.println(myQueue.deleteHead());
    23 
    24     }
    25 
    26 }
    27 
    28 class MyQueue {
    29 
    30     private Stack<Integer> stack1;
    31     private Stack<Integer> stack2;
    32 
    33     public MyQueue(Stack<Integer> stack1, Stack<Integer> stack2) {
    34         this.stack1 = stack1;
    35         this.stack2 = stack2;
    36     }
    37 
    38     public Boolean appendTail(Integer num) {
    39         Boolean result = false;
    40         if (null != num) {
    41             stack1.push(num);
    42             result = true;
    43         }
    44         return result;
    45     }
    46 
    47     public Integer deleteHead() {
    48         if (!stack2.isEmpty()) {
    49             return stack2.pop();
    50         }
    51 
    52         if (stack2.isEmpty() && !stack1.isEmpty()) {
    53             int length = stack1.size();
    54             for (int i = 0; i < length; i++) {
    55                 Integer temp = stack1.pop();
    56                 stack2.push(temp);
    57             }
    58             return stack2.pop();
    59         }
    60 
    61         return null;
    62     }
    63 
    64     public Stack<Integer> getStack1() {
    65         return stack1;
    66     }
    67 
    68     public void setStack1(Stack<Integer> stack1) {
    69         this.stack1 = stack1;
    70     }
    71 
    72     public Stack<Integer> getStack2() {
    73         return stack2;
    74     }
    75 
    76     public void setStack2(Stack<Integer> stack2) {
    77         this.stack2 = stack2;
    78     }
    79 
    80 }
  • 相关阅读:
    Ubuntu 12.04 下 Sublime Text 3 Build 3047 破解
    如何让Ubuntu 12.04 LTS更炫更具吸引力
    重装Ubuntu时如何保留/home分区中的数据
    【转】使用TCP协议连续传输大量数据时,是否会丢包,应如何避免?
    TCP协议三次握手过程分析
    狮子的预言
    来跟从我
    服役的灵
    追求良善
    安慰人心的主
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/7967505.html
Copyright © 2020-2023  润新知