出栈序列的合法性判断,数据结构陈越习题
如果是为了解决陈老师的课后习题,思路看课本上就行,这里我用java实现代码,容易看懂
和课本上的输入输出示范不同,我这里做了很多的输入输出标记,程序在运行的时候很容易看出应该输入什么,便于你理解
public class Judge {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
System.out.print("按顺序入栈的元素个数N");
int n = scanner.nextInt();
// 需要校验的出栈序列的个数
System.out.print("需要校验的出栈序列的个数");
int k = scanner.nextInt();
// 创建一个数组用来存储待校验的序列
int[] list = new int[n];
int count = 1;
while ( count <= k){
System.out.println("第"+count+"校验的序列");
// 将该序列存入一个数组中
for (int i = 0; i < list.length ; i++) {
System.out.print("第" +(i+1)+ "个数");
list[i] = scanner.nextInt();
}
// 开始校验
for (int i = 0,j = 0; i < n; i++) {
stack.push(i + 1);
while (stack.peek() == list[j]) {
j++;
stack.pop();
if (stack.empty()){
break;
}
}
}
if (stack.empty()){
System.out.println("该出栈序列合法");
}
else System.out.println("该出栈序列不合法");
count++;
}
}
}