import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
/**
* 栈是Vector的一个子类,实现了一个标准的先进后出的
* 案例操作实例:
* 实现一个栈,实现栈的基本功能上,再实现返回栈中最小值的元素的操作
*/
public class TestStack {
public static void main(String[] args) throws IOException {
MyStack myStack = new MyStack();
BufferedReader scanner= new BufferedReader(new InputStreamReader(System.in));
int N=Integer.parseInt(scanner.readLine());
for(int i=0;i<N;i++){
String []inputData=scanner.readLine().split(" ");
if(inputData[0].equals("push")){
myStack.push(Integer.parseInt(inputData[1]));
}
if(inputData[0].equals("pop")){
myStack.pop();
}
if(inputData[0].equals("getMin")){
myStack.getMin();
}
}
scanner.close();
}
}
class MyStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack() {
this.stackData = stackData;
this.stackMin = stackMin;
}
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum <= this.getMin()) {
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int pop() {
if(this.stackData.isEmpty()){
throw new RuntimeException("你的栈为空");
}
int value=this.stackData.pop();
if(value==this.getMin()){
this.stackData.pop();
}
return value;
}
public int getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("你的栈为空");
}
return this.stackMin.peek();//返回的是栈顶的元素
}
}
实现一个栈,实现栈的基本功能上,再实现返回栈中最小值的元素的操作
最新推荐文章于 2022-05-13 21:12:57 发布