解析:先将栈顶元素赋值给mini变量,然后做一个判断,只要栈顶元素小于该值就将值赋给mini然后弹出,大于或者等于也弹出,弹出之前将值存放在list集合中,最后还原栈时,用Collection.reverse()函数对list进行反转(后进先出原则)。
package offerPractical;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class StackMini {
// 控制台输入字符串转换整形数组
public int[] translate(String str) {
String[] emmer = str.split(",");
int[] sum = new int[emmer.length];
for (int i = 0; i < emmer.length; i++) {
sum[i] = Integer.parseInt(emmer[i]);
}
return sum;
}
public static void main(String[] args) {
StackMini stackmini = new StackMini();
System.out.println("请输入一串数组,数字之间用逗号隔开,该数组为树组元素进栈顺序");
Scanner in = new Scanner(System.in);
int[] sum = stackmini.translate(in.next());
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < sum.length; i++) {
stack.push(sum[i]);
}
List<Integer> list = new ArrayList<Integer>();
//第一次先将栈顶元素给mini,如果栈顶元素小于mini,则将小的栈顶元素值赋给mini
int mini = stack.peek();
while (!stack.empty()) {
list.add(stack.peek());
if (mini > stack.peek()) {
mini = stack.peek();
stack.pop();
} else {
stack.pop();
}
};
// 根据先进后出原则,还原栈,验证输出list
Collections.reverse(list);
stack.addAll(list);
for (Integer integer : list) {
System.out.println(integer);
}
// 输出结果
System.out.println("栈中最小元素值为" + mini);
}
}