我正在尝试在 C++ 中实现前缀中缀,这就是我目前所拥有的。输入应该是这样的:
/7+23
输出:
7/(2+3) or (7/(2+3))
但我得到的是:
(/)
这是我到目前为止编写的代码:
void pre_to_in(stack<char> eq) {
if(nowe.empty() != true) {
char test;
test = eq.top();
eq.pop();
if(test == '+' || test == '-' || test == '/' || test == '*') {
cout << "(";
pre_to_in(eq);
cout << test;
pre_to_in(eq);
cout << ")";
} else {
cout << test;
}
}
}
// somewhere in main()
char arr[30];
stack<char> stosik;
int i = 0;
cout << "write formula in prefix notation\n";
cin >> arr;
while(i < strlen(arr)) {
stosik.push(arr[i]);
i++;
}
pre_to_in(stc);
最佳答案
这是一个堆栈。先入后出。您需要反向输入字符串“32+7/”。
您使用了很多堆栈。在每次进入 pre_to_in() 时,都会复制堆栈。使用引用或指针,例如:
void pre_to_in(stack<char> &eq);
就这些。
附言统一名称(s/nowe/eq/g && s/stc/stosik/g)
关于c++ - 堆栈中缀的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877425/