您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java 实例 - 利用堆栈将中缀表达式转换成后缀表达式

2024/3/22 17:49:08发布25次查看
以下实例演示了如何使用堆栈进行表达式的堆栈将中缀(infix)表达式转换成后缀(postfix)表达式:
/* author by w3cschool.cc intopost.java */import java.io.ioexception;public class intopost { private stack thestack; private string input; private string output = ""; public intopost(string in) { input = in; int stacksize = input.length(); thestack = new stack(stacksize); } public string dotrans() { for (int j = 0; j < input.length(); j++) { char ch = input.charat(j); switch (ch) { case '+': case '-': gotoper(ch, 1); break; case '*': case '/': gotoper(ch, 2); break; case '(': thestack.push(ch); break; case ')': gotparen(ch); break; default: output = output + ch; break; } } while (!thestack.isempty()) { output = output + thestack.pop(); } system.out.println(output); return output; } public void gotoper(char opthis, int prec1) { while (!thestack.isempty()) { char optop = thestack.pop(); if (optop == '(') { thestack.push(optop); break; } else { int prec2; if (optop == '+' || optop == '-') prec2 = 1; else prec2 = 2; if (prec2 < prec1) { thestack.push(optop); break; } else output = output + optop; } } thestack.push(opthis); } public void gotparen(char ch){ while (!thestack.isempty()) { char chx = thestack.pop(); if (chx == '(') break; else output = output + chx; } } public static void main(string[] args) throws ioexception { string input = "1+2*4/5-7+3/6"; string output; intopost thetrans = new intopost(input); output = thetrans.dotrans(); system.out.println("postfix is " + output + '\n'); } class stack { private int maxsize; private char[] stackarray; private int top; public stack(int max) { maxsize = max; stackarray = new char[maxsize]; top = -1; } public void push(char j) { stackarray[++top] = j; } public char pop() { return stackarray[top--]; } public char peek() { return stackarray[top]; } public boolean isempty() { return (top == -1); } }}
以上代码运行输出结果为:
124*5/+7-36/+postfix is 124*5/+7-36/+
以上就是java 实例 - 利用堆栈将中缀表达式转换成后缀表达式的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product