所以基本上我试图解决这部分问题的方法是使用bst。我相信bst是最好的方法,因为一旦它在树中,你可以从底部开始,从左,上,右走,并进行中缀表达。例如,如果你取rpn表达式“5 4 +”并从结尾开始,“+”是树的根,左右节点是5和4.然后,从左边开始,到达顶部和右边你得到5 + 4.规范是我必须正确地为一些更大的表达式括起一切; “5 4 + 3 * 2 /”必须变成“((5 + 5)* 3)/ 2”。
我的中缀函数现在只是以线性形式打印出树。显然,我试图建造树的方式有问题,因为“1 5 A”被打印为“A 5 5”..实际上无论我输入什么,它只会打印出三件事,它只告诉我它最多存储三件东西..无论如何,我感觉形状不好的程序,而且我很尴尬,任何帮助将不胜感激。可能有一些明显的错误,但我的大脑太油腻,无法注意到它们中的任何一个。我的其他大学课程让人很难专注于编程。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#define MAX 100;
#define OP_EVAL "-e"
#define OP_INFX "-c"
#define OP_GENI "-g"
struct btree {
int data;
int isop;
struct btree *left;
struct btree *right;
};
typedef struct btree node;
int is_oper(char ch);
node*
insert(char** argv, int index){
node *tree;
if(index < 1)
return NULL;
if(is_oper(argv[index][0])){
tree = (node*)malloc(sizeof(node));
tree->data = (int)argv[index][0];
index--;
tree->right = insert(argv, index);
tree->left = insert(argv, index);
tree->isop = 1;
return tree;
}
else{
tree = (node*)malloc(sizeof(node));
tree->right = NULL;
tree->left = NULL;
tree->data = atoi(&argv[index][0]);
tree->isop = 0;
index--;
return tree;
}
}
enum method
{
EVAL,
INFX,
GENI
};
int
is_option(const char *str)
{
return (strcmp(str, OP_EVAL) == 0) ||
(strcmp(str, OP_INFX) == 0) ||
(strcmp(str, OP_GENI) == 0);
}
enum method
manip_method(const char *arg)
{
if (strcmp(arg, OP_EVAL) == 0)
return EVAL;
else if (strcmp(arg, OP_INFX) == 0)
return INFX;
else if (strcmp(arg, OP_GENI) == 0)
return GENI;
else
return 0;
}
int
is_oper(char ch){
if(ch == 'A' || ch == 'S' || ch == 'X' || ch == 'D' || ch == 'M')
return 1;
else
return 0;
}
void
infix(node *root){
if(root != NULL){
if(root->isop){
printf("%c ",(char)root->data);
}
else{
printf("%d ", root->data);
}
infix(root->left);
infix(root->right);
}
}
int
main(int argc, char *argv[])
{
node *root;
root = NULL;
enum method method;
int x;
if (argc >= 4){
if (is_option(argv[1])){
if (argc < 5){
printf("not a valid calculatable expression, exiting now...\n");
exit (EXIT_FAILURE);
}
x = 2;
method = manip_method(argv[1]);
}
else {
x = 1;
method = EVAL;
}
} else {
printf("need option and or a valid reverse polish notation expression, exiting now...\n");
exit (EXIT_FAILURE);
}
root = insert(argv, argc-x);
infix(root);
exit (EXIT_SUCCESS);
}