zoukankan      html  css  js  c++  java
  • 设计一个有getMin功能的栈

    设计两个栈,一个栈是stackData,另一个栈是stackMin.

    思路:

    压入数据:

    1.若有数据到来则将数据压入stackData,若stackMin为空,则将数据压入stackMin

    2.若stackMin不为空,则比较压入的数据和stackMin的栈顶元素的大小,若小于或等于则压入,若大于则不压入

    弹出数据:

    1.若stackData弹出的数据等于stackMin的栈顶数据则stackMin也弹出数据.

    具体代码如下:

    package chapter1;
    
    import java.util.Scanner;
    import java.util.Stack;
    
    public class pro1_getMin {
        private Stack<Integer> stackData ;
        private Stack<Integer>stackMin ;
        
        public pro1_getMin() {
            this.stackData = new Stack<Integer>() ;
            this.stackMin = new Stack<Integer>() ;
        }
        
        public  void  push(int newNum) {
            stackData.push(newNum) ;
            if(stackMin.isEmpty()) {
                stackMin.push(newNum) ;
            }
            else {
                if(newNum <= stackMin.peek()) {
                    stackMin.push(newNum) ;
                }
            }
        }
        
        public int pop() {
            if(stackData.isEmpty()) {
                throw new RuntimeException("Your stack is empty!") ;
            }
            int value = stackData.pop();
            if(value == stackMin.peek()) {
                stackMin.pop();
            }
            return value ;
        }
        
        public int getMin() {
            if(stackMin.isEmpty()) {
                throw new RuntimeException("Your stack is empty!") ;
            }
            return stackMin.peek();
        }
    
    }
  • 相关阅读:
    怎么查看京东店铺的品牌ID
    PPT编辑的时候很卡,放映的时候不卡,咋回事?
    codevs 1702素数判定2
    codevs 2530大质数
    codevs 1488GangGang的烦恼
    codevs 2851 菜菜买气球
    hdu 5653 Bomber Man wants to bomb an Array
    poj 3661 Running
    poj 1651 Multiplication Puzzle
    hdu 2476 String Painter
  • 原文地址:https://www.cnblogs.com/chwy/p/5611409.html
Copyright © 2011-2022 走看看