算法第四版1.3背包、队列和栈:习题1.3.45

个人理解,该题目让设计两个算法:

1.有一批数字与"-"混合的序列,是数字则将该数字入栈,是"-"将数字出栈,判断栈是否向下溢出。

2.已知一个数字序列(序列中数字为0到N-1,可以混乱),判断这个序列能否由将数字0到N-1的入栈出栈生成(入栈时顺序由0到N-1,出栈可在数字入栈之间的任何时候进行),如果可以,打印出数字的入栈出栈顺序,出栈用"-"表示。也就是用程序判断1.3.3题。

import edu.princeton.cs.algs4.StdOut;

public class E1_3_45 {
    public static void main(String[]args){
        String[] strunderflow={"1","-","-"};
        if (isUnderflow(strunderflow))
            StdOut.println("UnderFlow");
        String[] str={"2","5","6","7","4","8","9","3","1","0"};//generated
        if (stackIsGenerate(str)!=null) {
            Queue queue = stackIsGenerate(str);
            for (String s : queue)
                StdOut.print(s + " ");
            StdOut.println();
        }
        else
            StdOut.println("don't generated");

        String[] str1={"0","4","6","5","3","8","1","7","2","9"};//don't generated
        if (stackIsGenerate(str1)!=null) {
            Queue queue1 = stackIsGenerate(str1);
            for (String s : queue1)
                StdOut.print(s + " ");
            StdOut.println();
        }
        else
            StdOut.println("don't generated");
    }
    public static boolean isUnderflow(String[]queue){
        boolean result=false;
        int count=0;
        for (int i=0;i stackIsGenerate(String[]queue){
        Queue stringQueue=new Queue<>();
        Stack stack=new Stack<>();
        int insertedMaximum=-1;
        for (int j=0;jinsertedMaximum){
                for (int i=insertedMaximum+1;i<=Integer.parseInt(queue[j]);i++) {
                    stack.push(i);
                    stringQueue.enqueue(Integer.toString(i));
                }
                stack.pop();stringQueue.enqueue("-");
                insertedMaximum=Integer.parseInt(queue[j]);
            }
            else {
                int currentMaximum=stack.pop();stringQueue.enqueue("-");
                if (Integer.parseInt(queue[j])==currentMaximum){
                    //already poped
                }
                else
                    return null;
            }
        }
        return  stringQueue;
    }
}

 

你可能感兴趣的:(算法第四版1.3背包,队列和栈课后习题)