java 编程思想 11章 持有对象 练习15

练习15 (4)栈在编程语言中用来对表达式求值。请使用Stack对下面表达式求值,其中,“+“表示”将后面的字母压进栈”,而”-”表示”弹出栈顶字母并打印它”:
“+U+n+c—+e+r+t—+a-+i-+n+t+y—+-+r+u–+l+e+s—”

package com.js.fill.mycollision;

import java.util.LinkedList;

public class Stack {
    private LinkedList storge = new LinkedList();

    public void push(T v) {
        storge.addFirst(v);
    }

    public T pop() {
        return storge.removeFirst();
    }

    public T peek() {
        return storge.getFirst();
    }

    public String toString() {
        return storge.toString();
    }

    public static void main(String[] args) {
        String expression = "+U+n+c---+e+r+t---+a-+i-+n+t+y---+-+r+u--+l+e+s---";
        Stack stack = new Stack<>();
        for (int i = 0; i < expression.length(); i++) {
            switch (expression.charAt(i)) {
            case '+':
                Character c = expression.charAt(++i);
                if (c != '-' && c != '+') {
                    stack.push(expression.charAt(i));
                    System.out.print("元素【 ");
                    System.out.print(expression.charAt(i));
                    System.out.print("】入站 :");
                    System.out.println(stack.toString());
                }
                break;
            case '-':
                System.err.print("元素【 ");
                System.err.print(stack.pop());
                System.err.print("】出站 :");
                System.err.println(stack.toString());
                break;
            default:
                break;
            }
        }
       /*    输出:
            元素【 U】入站 :[U]
            元素【 n】入站 :[n, U]
            元素【 c】入站 :[c, n, U]
            元素【 c】出站 :[n, U]
            元素【 n】出站 :[U]
            元素【 U】出站 :[]
            元素【 e】入站 :[e]
            元素【 r】入站 :[r, e]
            元素【 t】入站 :[t, r, e]
            元素【 t】出站 :[r, e]
            元素【 r】出站 :[e]
            元素【 e】出站 :[]
            元素【 a】入站 :[a]
            元素【 a】出站 :[]
            元素【 i】入站 :[i]
            元素【 i】出站 :[]
            元素【 n】入站 :[n]
            元素【 t】入站 :[t, n]
            元素【 y】入站 :[y, t, n]
            元素【 y】出站 :[t, n]
            元素【 t】出站 :[n]
            元素【 n】出站 :[]
            元素【 r】入站 :[r]
            元素【 u】入站 :[u, r]
            元素【 u】出站 :[r]
            元素【 r】出站 :[]
            元素【 l】入站 :[l]
            元素【 e】入站 :[e, l]
            元素【 s】入站 :[s, e, l]
            元素【 s】出站 :[e, l]
            元素【 e】出站 :[l]
            元素【 l】出站 :[]
        *///:~
    }
}

你可能感兴趣的:(java)