《java数据结构与算法》笔记-CH4-8栈结构实现后缀表达式计算结果

/**
 * 中缀表达式转换成后缀表达式: 从输入(中缀表达式)中读取的字符,规则: 操作数: 写至输出 左括号: 推其入栈 右括号: 栈非空时重复以下步骤-->
 * 若项不为(,则写至输出; 若项为(,则推出循环 operator(opThis): 若栈为空,推opThis; 否则,重复-->
 * 弹出一项,若项为(,推其入栈; 若项为operator,且 若opTop=opThis,输出opTop,
 * 若opTop='0' && c<='9'){
				stack.push(c);
			}else{
				num2 = (int)(stack.pop()-'0');
				num1 = (int)(stack.pop()-'0');
				switch (c) {
				case '+':
					result = num1+num2;
					break;
				case '-':
					result = num1-num2;
					break;
				case '*':
					result = num1*num2;
					break;
				case '/':
					result = num1/num2;
					break;
				default:
					result = 0;
					break;
				}
				stack.push((char)(result+'0'));
			}
		}
		result = (int)(stack.pop()-'0');
		return result;
	}
}

public class InfixDemo {
	/**
	 * 读取字符串
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getString() throws IOException {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader reader = new BufferedReader(isr);
		return reader.readLine();
	}
	public static void main(String[] args) throws IOException {
		String input, output;
		while(true){
			System.out.println("enter:");
			System.out.flush();
			input = getString();
			if(input.equals(""))
				break;
			InToPost i = new InToPost(input);
			output = i.doTrans();
			System.out.println(output);
			System.out.println(i.doParse(output));
		}
	}
}

转载于:https://www.cnblogs.com/fstack/p/5617256.html

你可能感兴趣的:(《java数据结构与算法》笔记-CH4-8栈结构实现后缀表达式计算结果)