zoukankan      html  css  js  c++  java
  • 栈结构实现队列结构

    package arithmetic;
    
    import java.util.Stack;
    
    public class TwoStacksQueue {
        public Stack<Integer> stackPush;
        public Stack<Integer> stackPop;
    
        public TwoStacksQueue() {
            stackPush = new Stack<>();
            stackPop = new Stack<>();
        }
    
        public void pushToPop() {
            //pop栈为空时才可以导入
            if (stackPop.isEmpty()) {
                //只要导入就需要将push栈全部导入pop栈
                while (stackPush != null) {
                    stackPop.push(stackPush.pop());
                }
            }
        }
    
        public void add(int value) {
            stackPush.push(value);
            pushToPop();
        }
    
        public int poll() {
            if (stackPop.isEmpty() && stackPush.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return stackPop.pop();
        }
    
        public int peek() {
            if (stackPop.empty() && stackPush.empty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return stackPop.peek();
        }
    
        public static void main(String[] args) {
            TwoStacksQueue test = new TwoStacksQueue();
            test.add(1);
            test.add(2);
            test.add(3);
            System.out.println(test.peek());
            System.out.println(test.poll());
            System.out.println(test.peek());
            System.out.println(test.poll());
            System.out.println(test.peek());
            System.out.println(test.poll());
        }
    }
  • 相关阅读:
    UIButton 动态改变文本闪烁问题
    利用GDataXML解析XML文件
    限制键盘只能输入数字
    获得view所在的控制器
    使用Canvas绘制简单的时钟控件
    Spring整合ActiveMq消息队列
    Symmetric Key Encryption DES
    OSPF 高级实验
    OSPF 基础实验
    EIGRP 高级实验
  • 原文地址:https://www.cnblogs.com/yanghailu/p/12775027.html
Copyright © 2011-2022 走看看