剑指offer21,包含min函数的栈(Java实现)

xiaoxiao2021-03-01  20

import java.util.Stack; /**  * 具有getmin功能的栈  * @author lenovo047  *  */

public class test21 {     private static Stack<Integer> stackData = new Stack<>();     private static Stack<Integer> stackMin = new Stack<>();          public static void push(int num){         if(stackMin.isEmpty()){    //栈为空,直接放进去             stackMin.push(num);         } else if(stackMin.peek() > num){   //新数比栈顶元素小,放新数             stackMin.push(num);         } else {                                              //新数比栈顶元素大,放老数             stackMin.push(stackMin.peek()); //peek只是复制这个数         }         stackData.push(num);     }          public static int pop(){         if(stackData.isEmpty()){             throw new RuntimeException("栈为空");         }         stackMin.pop();         return stackData.pop();     }     public static int getMin(){         if(stackMin.isEmpty()){             throw new RuntimeException("栈为空");         }         return stackMin.peek();     }

}  

转载请注明原文地址: https://www.6miu.com/read-4049996.html

最新回复(0)