队列-运算后缀表达式

来源:互联网 发布:虚拟充值软件靠谱吗 编辑:程序博客网 时间:2024/06/07 01:27
package d_queue.E_SuffixExpressionValue;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * 运算后缀表达式
 * 
 * @author Administrator
 *
 */
public class InfixApp {
public static void main(String[] args) throws IOException {
String input;
int output;
while (true) {
System.out.print("Enter infix:");
System.out.flush();
input = getString();
if (input.equals(""))
break;
ParsePost theParse = new ParsePost(input);
output = theParse.doTrans();
System.out.println("Postfix is " + output);
}
}


public static String getString() throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in))
.readLine();
return s;
}
}package d_queue.E_SuffixExpressionValue;


public class ParsePost {// infix to postfix conversion 中缀转后缀转换
private StackX theStackX;
private String input;


public ParsePost(String in) {
input = in;
theStackX = new StackX(input.length());
}


public int doTrans() {// do translation to postfix 转变后缀
int num1, num2, interAns;
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
theStackX.displaysStack("For:" + ch);
if (ch >= '0' && ch <= '9')
theStackX.push((int) (ch - '0'));
else {
num2 = theStackX.pop();
num1 = theStackX.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;
}
theStackX.push(interAns);}
}
interAns=theStackX.pop();
return interAns;
}
}package d_queue.E_SuffixExpressionValue;


public 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 i) {
stackArray[++top] = i;
}


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[n];
}


/*
* 显示堆栈
*/
public void displaysStack(String s) {
System.out.print(s);
System.out.print(" Stack {bottom-->top}:");
for (int j = 0; j < size(); j++) {
System.out.print(peekN(j));
System.out.print(" ");
}
System.out.println();
}
}
0 0
原创粉丝点击