第一种方式:
import java.util.Stack;
public class MyStack1 {
public static void main(String[] args) {
MyStack1Real myStack1Real = new MyStack1Real();
for (int i = 0; i < 10; i++) {
myStack1Real.push(i);
}
myStack1Real.push(-1);
System.out.println(myStack1Real.getMin());
}
}
class MyStack1Real {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack1Real() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int newNum) {
if (stackMin.isEmpty()) {
stackMin.push(newNum);
} else if (newNum <= this.getMin()) {
stackMin.push(newNum);
}
stackData.push(newNum);
}
public int pop() {
if (this.stackData.peek() == this.stackMin.peek()) {
this.stackData.pop();
return this.stackMin.pop();
} else {
return this.stackMin.pop();
}
}
public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("your stack is empty!");
} else {
return this.stackMin.peek();
}
}
}
第二种方式:
package stackAndQueue;
import java.util.Stack;
public class MyStack2 {
public static void main(String[] args) {
MyStack1Real myStack1Real = new MyStack1Real();
for (int i = 0; i < 10; i++) {
myStack1Real.push(i);
}
myStack1Real.push(-8);
System.out.println(myStack1Real.getMin());
}
}
class MyStack2Real {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack2Real() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackData.push(newNum);
this.stackMin.push(newNum);
} else if (newNum <= this.getMin()) {
this.stackData.push(newNum);
this.stackMin.push(newNum);
} else {
this.stackData.push(newNum);
this.stackMin.push(this.stackMin.peek());
}
}
public int pop(int newNum) {
this.stackMin.pop();
return this.stackData.pop();
}
public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("your stack is empty");
} else {
return stackMin.peek();
}
}
}