Java实现堆栈小应用

来源:互联网 发布:vue.js html 编辑:程序博客网 时间:2024/05/21 07:57
package D0718;/* * 铁轨问题: * 样例输入: * 5 * 1 2 3 4 5 * 5 * 5 4 1 2 3 * 6 * 6 5 4 3 2 1 * 样例输出: * Yes * No * Yes * 题目大概意思:(堆栈的应用)判断输入的一串数字是否符合堆栈顺序就ok * 这里提供两种解法:一种用数组,一种用LinkedList * */import java.util.LinkedList;import java.util.Scanner;public class Track {public static void main(String[] args) {//fun1(); fun2();}private static void fun1() {// 用数组实现时只需要一个表示堆栈的数组和一个栈顶指针即可。Scanner sc = new Scanner(System.in);int n;int[] arr;int top;// 栈顶指针while (sc.hasNext()) {n = sc.nextInt();arr = new int[n+1];top = 0;for (int i = 1; i <= n; i++) {arr[i] = sc.nextInt();}boolean ok = true;int a = 1, b = 1;while(b<=n){if(a==arr[b]){a++;b++;}else if(top>0&&arr[top]==arr[b]){top--;b++;}else if(a<=n)arr[++top]=a++;else{ok = false;break;}}System.out.println(ok ? "Yes" : "No");}}private static void fun2() {Scanner sc = new Scanner(System.in);int n;int[] arr;LinkedList<Integer> ll ;while (sc.hasNext()) {n = sc.nextInt();arr = new int[n+1];ll = new LinkedList<Integer>();for (int i = 1; i <= n; i++) {arr[i] = sc.nextInt();}boolean ok = true;int a = 1, b = 1;while(b<=n){if(a==arr[b]){a++;b++;}else if(!ll.isEmpty()&&ll.peek()==arr[b]){ll.pop();b++;}else if(a<=n)ll.push(a++);else{ok = false;break;}}System.out.println(ok ? "Yes" : "No");}}}