我正在寻找代码wchich使用递归解析前缀表达式。主要是在C ++中,但它可以用其他语言,我会翻译。感谢。
答案 0 :(得分:1)
自己很容易做到(你只需要为操作员提供一个堆栈(有时候/可选择第一个任期)。
但如果你真的不想做太多工作,可以点击链接:
prefix notation string to int conversion
如果需要使用递归,则基本上将函数中的局部变量用作堆栈中的单个元素。
EG。伪C ++代码如下:
int naughtyglobalendindex = 0;
int parse(string str) {
if (/* str starts off with an integer */) return the integer;
char operator;
operator = ?? // you will need to get the first op here. Maybe sscanf(str,"%c",&operator) or similar
// get first argument
int first = parse(/* str with 1st operator removed */);
// get 2nd integer argument
int second = parse(/* str - get substring from naughtyglobalendindex to end*/)
// return first operator second <- this is pseudocode
// in effect you want a switch clause
switch (operator) {
case '+': return first + second;
case '-': return first - second; // and so on
}
}
您可以将伪代码转换为实际的C ++,如果需要,可以根据需要修复全局naughtyglobalendindex
变量。