我正在研究一個項目,我需要評估一個反向波蘭表示法或將rpn表達式轉換爲中綴表示法。我通過將表達式的所有元素推入堆棧然後從堆棧中彈出每個元素並將其插入到抽象語法樹中來完成此操作。從那裏我將遍歷樹來完成評估和轉換操作。這是我到目前爲止從堆棧創建抽象語法樹
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct snode
{
char datum;
struct snode* bottom;
};
struct tnode
{
char datum;
struct tnode* left;
struct tnode*right;
};
struct snode*
push(struct snode* stack, char x) {
struct snode *S = (struct snode*)malloc(sizeof(struct snode));
S->datum = x;
S->bottom = stack;
return S;
}
struct snode*
pop(struct snode* stack) {
struct snode *S;
if (stack == NULL)
return NULL;
S = stack->bottom;
free(stack);
return S;
}
char
peek(struct snode* stack){
return stack->datum;
}
struct tnode*
create_node(char x){
struct tnode* tmp;
tmp = (struct tnode*)malloc(sizeof(struct tnode));
tmp->datum = x;
tmp->right = NULL;
tmp->left = NULL;
return tmp;
}
void
print_table(struct tnode *AST){
if(AST !=NULL){
print_table(AST->left);
printf("%c ", AST->datum);
print_table(AST->right);
}
}
struct tnode*
build_tree(struct snode *S)
{
struct tnode* root;
if (S == NULL)
return NULL;
char top = peek(S);
if (top == 'A' || top == 'S' || top == 'X' || top == 'D' || top == 'M')
{
root = create_node(top);
S = pop(S);
root->right = build_tree(S);
S = pop(S);
root->left = build_tree(S);
return root;
}
root= create_node(top);
return root;
}
int
main(int argc, const char *argv[])
{
int i = 1;
struct tnode *tree = NULL;
struct snode *stack = NULL;
char value;
while (argv[i]!= NULL)
{
value = argv[i][0];
stack = push(stack, value);
i++;
}
tree = build_tree(stack);
print_table(tree);
printf("\n");
return EXIT_SUCCESS;
}
我的問題是,此代碼只對每個rpn表達式不起作用。例如:
./project 7 4 A 3 S
輸出
7 A 4 S 3
這是正確的。但
./project 1 2 X 3 4 X A
輸出
A 3 X 4
這顯然是不正確的。林肯定我的問題是在我的build_tree函數,但我不知道如何以不同的方式做一個build_tree。 此外,當我有作爲
./project 12 3 D 2 D
這樣的表達式的輸出是怎麼來的
1 D 3 D 2
,而不是
12 D 3 D 2
謝謝所有幫助。任何有關如何更改我的代碼以使項目的其餘部分更簡單的輸入也值得讚賞!
你不需要用中綴表示法來控制表達式評估命令嗎? –
現在即時我剛剛到了一個點,我知道樹正在建設正確@NikolaiNFetissov – etorr96
'1'與'12'在你最後一個例子很容易 - 你只使用每個'argv [i]的第一個字符' 。 –