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

来源:互联网 发布:ubuntu查看opencv路径 编辑:程序博客网 时间:2024/06/05 07:14
题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。

要求:
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);}}

原创粉丝点击