您的位置:首页 > 编程语言 > Java开发

栈——设计一个有getmin功能的栈

2017-08-19 09:46 357 查看
题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。

要求:
1、pop、push、getMin操作的时间复杂度都是O(1)。
2、设计的栈类型可以输用现成的栈结构。
思路:使用两个栈,一个用来保存栈中的元素,另一个用于保存每步的最小值
其实就是左神的思路啦~
代码:
package getmin;import java.util.Stack;import javax.management.RuntimeErrorException;public class MyStack {private Stack<Integer> stackData;private Stack<Integer> stackMin;public MyStack(){this.stackData = new Stack<Integer>();this.stackMin = new Stack<Integer>();}public void push(int newNum){if(this.stackMin.isEmpty()){this.stackMin.push(newNum);}else if(newNum <= this.getmin()){this.stackMin.push(newNum);}else{this.stackData.push(newNum);}}public int pop(){if(this.stackData.isEmpty()){throw new RuntimeException("your stack is empty");}int value = this.stackData.pop();if(value == this.getmin()){this.stackMin.pop();}return value;}public int getmin(){if(this.stackMin.isEmpty()){throw new RuntimeException("your stack is empty");}return this.stackMin.peek();}public static void main(String args[]){MyStack sta = new MyStack();sta.push(3);sta.push(4);sta.push(2);sta.push(1);sta.pop();int min = sta.getmin();System.out.println(min);}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法