数据结构-栈-计算后缀表达式
2016-09-29 10:32
513 查看
package com.jikefriend.socket.datastructure.collection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * 计算后缀表达式 */ public class Postfix { /** * 用于存放数字的栈 */ final static class StackX { private int maxSize; private int[] stackArray; private int top; public StackX(int s) { maxSize = s; stackArray = new int[maxSize]; top = -1; } public void push(int c) { stackArray[++top] = c; } public int pop() { return stackArray[top--]; } public int peek() { return stackArray[top]; } public boolean isEmpty() { return top == -1; } public int size() { return top + 1; } public int peekN(int n) { return stackArray ; } public void displayStack(String s) { System.out.print(s); System.out.print("Stack (bottom --> top): "); for (int i = 0; i < size(); i++) { System.out.print(peekN(i) + " "); } System.out.println(); } } /** * 计算后缀表达式的结果 */ final static class ParsePost { private StackX theStack; private String input; public ParsePost(String s) { input = s; } public int doParse() { theStack = new StackX(20); char ch; int j; int num1, num2, interAns; for (j = 0; j < input.length(); j++) { ch = input.charAt(j); theStack.displayStack("" + ch + " "); if (ch >= '0' && ch <= '9') { theStack.push((int)(ch - '0')); } else { num2 = theStack.pop(); num1 = theStack.pop(); switch (ch) { case '+': interAns = num1 + num2; break; case '-': interAns = num1 - num2; break; case '*': interAns = num1 * num2; break; case '/': interAns = num1 / num2; break; default: interAns = 0; break; } theStack.push(interAns); } } interAns = theStack.pop(); return interAns; } } public static void main(String[] args) throws IOException{ String input; int output; while (true) { System.out.print("Enter postfix: "); System.out.flush(); input = getString(); if (input.equals("")) break; ParsePost theParse = new ParsePost(input); output = theParse.doParse(); System.out.println("Evaluates to " + output); } } public static String getString() throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); return s; } }
摘自《java数据结构与算法(第二版)》 [美] Robert Lafore 著
相关文章推荐
- c++ 数据结构 利用顺序栈计算后缀表达式的值
- C++数据结构与STL--栈的应用--后缀表达式的计算
- 数据结构6:使用栈计算逆波兰表达式
- 数据结构算法之表达式自动计算
- 数据结构之栈----PTA题目7-20表达式转换(中缀转后缀)
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构基础之后缀表达式与中缀表达式的相互推导
- 数据结构与算法Java版——中缀表达式转后缀表达式
- 数据结构之应用"栈(Stack)"实现: 解析算术表达式及计算
- [数据结构与算法]栈的应用:计算 2*2+(10-2)/(101-50*2)*3-2+5 表达式的值
- 栈的应用:通过用户输入后缀表达式,利用数据结构栈计算其结果值。
- 中缀表达式转换为后缀表达式-数据结构
- 表达式计算3 +-*/^() 数据没有负数 后缀表达式
- 数据结构上机题目4--后缀表达式求值
- 【数据结构】利用后缀表达式求表达式的值
- 数据结构与算法笔记 lesson 12 中缀表达式转后缀表达式
- 《java数据结构与算法》笔记-CH4-8栈结构实现后缀表达式计算结果
- 数据结构之 栈和队列---算术表达式的转换(前缀+中缀+后缀)
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)