入栈顺序为0,1,2,3,4,5,6,7,8,9
入栈出栈操作可以随意交替进行,判断出栈顺序是否合理
(之前看浙大的数据结构mooc的时候遇到了这个问题,当时只看了一章就半途而废了。这次重新看java的数据结构入门书,遇到了这个习题,自己用java实现了一下,测试结果正确)
--------------------------------------------------------------------------------------------------------------------------------
首先是stack的实现
package algorithms; import java.util.Iterator; //栈顶是first节点,入栈出栈都是对first操作 public class Stack<Item> implements Iterable<Item>{ private Node first; private int N; //元素数量 private class Node{ Item item; Node next; } public boolean isEmpty(){ return first==null; } public int size() { return N; } public void push(Item item) { Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; N++; } public Item pop() { Item item = first.item; first = first.next; N--; return item; } public Iterator<Item> iterator(){ return new ListIterator(); } private class ListIterator implements Iterator<Item>{ private Node current = first; public boolean hasNext() { return current != null; } public Item next() { Item item = current.item; current = current.next; return item; } public void remove() { } } public static void main(String[] args) { Stack<String> s = new Stack<String>(); while(!StdIn.isEmpty()) { String item = StdIn.readString(); if(! item.equals("-") ){ s.push(item); } else if( ! s.isEmpty() ){ StdOut.print(s.pop()+""); } } StdOut.println("("+s.size()+" left on stack)"); } }---------------------------------------------------------------------------------------------------------------------------------
package algorithms; //这个类用来判断出栈顺序是否合理 public class StackDecision { public static void main(String[] args) { //待判定的出栈顺序 int[] a = {4, 3, 2, 1, 0, 9, 8, 7, 6, 5}; int[] b = {4, 6 ,8, 7 ,5 ,3 ,2 ,9 ,0 ,1}; int[] c = {2, 5, 6 ,7 ,4 ,8 ,9, 3, 1, 0}; int[] d = {4 ,3, 2 ,1, 0, 5, 6, 7, 8 ,9}; int[] e = {1, 2 ,3 ,4 ,5 ,6, 9, 8, 7 ,0}; int[] f = { 0 ,4 ,6, 5, 3, 8, 1, 7, 2, 9}; int[] g = { 1, 4, 7 ,9, 8, 6, 5, 3, 0, 2}; int[] h = {2, 1, 4, 3, 6, 5, 8, 7, 9, 0}; int[][] list = {a,b,c,d,e,f,g,h}; for(int[] x:list ) { StdOut.println( isPossible(x) ); } } public static boolean isPossible(int[] x){ int[] out = new int[x.length]; //待检测的出栈顺序 for(int i = 0;i<x.length;i++) { //保护性复制 out[i] = x[i]; } int item_in = 0;//下一个入栈的元素 Stack<Integer> stack = new Stack<Integer>(); for(int out_item :out) { //依次处理出栈顺序中的每个元素 if(item_in<=out_item) { //还没有入栈则需要入栈 for(int k = item_in;k<=out_item;k++) { //要出栈必先将它以及它之前的全部入栈 ,如果已入栈则不会进入for循环 stack.push(k); } item_in = out_item+1; } if(stack.pop() != out_item ) { //出栈的元素与预期元素不同 return false; } } return true; } }