package leetcode;
import java.util.Stack;
class demo15 {
Stack<Integer> dataStack;
Stack<Integer> minStack;
public demo15() {
//为什么要写在构造方法里面,写在上面不行么
dataStack=new Stack<>();
minStack=new Stack<>();
}
public void push(int x) {
dataStack.push(x);
if (minStack.isEmpty()||x<=minStack.peek()){
minStack.push(x);
}
}
public void pop() {
int x=dataStack.pop();
if (x==minStack.peek()){
minStack.pop();
}
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
public static void main(String[] args) {
demo15 s=new demo15();
s.push(-2);
s.push(0);
s.push(-3);
s.getMin();
s.pop();
s.top();
System.out.println(s.getMin());
}
}
试了一下写外面也可以
package leetcode;
import java.util.Stack;
class demo15 {
Stack<Integer> dataStack =new Stack<Integer>();
Stack<Integer> minStack =new Stack<Integer>();
public demo15() {
// dataStack=new Stack<>();
// minStack=new Stack<>();
}
public void push(int x) {
dataStack.push(x);
if (minStack.isEmpty()||x<=minStack.peek()){
minStack.push(x);
}
}
public void pop() {
int x=dataStack.pop();
if (x==minStack.peek()){
minStack.pop();
}
}
public int top() {
return dataStack.peek();
}
public int getMin() {
return minStack.peek();
}
public static void main(String[] args) {
demo15 s=new demo15();
s.push(-2);
s.push(0);
s.push(-3);
s.getMin();
s.pop();
s.top();
System.out.println(s.getMin());
}
}