实现一个特殊的栈,在实现栈的基本功的基础上,再实现返回栈中最小元素的操作
这道题本身很简单,比较复杂的地方是,在牛客网上利用scanner函数输入数据的时候,有很多的坑。题目本身倒是真没花费我多少时间。希望我的这份代码能帮到你。如果你有更好的方法,还请不吝赐教。
代码如下:
import java.util.Scanner;
import java.util.Stack;
public class Main {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public Main() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int num) {
this.stackData.push(num);
if (this.stackMin.isEmpty()) {
this.stackMin.push(num);
} else if (num <= this.getMin()) {
this.stackMin.push(num);
}
}
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) {
Main main = new Main();
Scanner sc = new Scanner(System.in);
int epoch = sc.nextInt();
// 这句非常重要,跳到第二行
sc.nextLine();
for (int i = 0; i < epoch; i++) {
String methods = sc.nextLine();
String[] method = methods.split(" ");
if (method[0].equals("push")) {
int num = Integer.parseInt(method[1]);
main.push(num);
}
if (method[0].equals("pop")) {
main.pop();
}
if (method[0].equals("getMin")) {
System.out.println(main.getMin());
}
}
}
}
来源:CSDN
作者:IronWring_Fly
链接:https://blog.csdn.net/IronWring_Fly/article/details/103546567