第一种方式:
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();
}
}
}

本文介绍了一种使用两个栈来实现带有获取最小值功能的数据结构的方法。通过维护一个辅助栈,可以在常数时间内得到栈中当前的最小元素。文章提供了两种实现方式,并附有示例代码。
1545

被折叠的 条评论
为什么被折叠?



