我在插入我的運算式樹時遇到了麻煩。我的運算式樹是由運算式節點組成的。這些運算式節點包含一個列舉、操作或一個字串。每個運算式節點也有一個指向運算式的 leftArgument/rightArgument 指標(leftNode 地址和 rightNode 地址)。
當然,我的 addNode 函式顯然沒有完全實作,但是我希望這段代碼能夠插入 (5) 個運算式節點,并且每個節點都被插入到左邊,從而創建一個非常左重的樹。
然而,在執行時,它似乎只改寫了我的樹中第二層的運算式節點。在我的main()或addNode()函式中,我的指標/地址出了問題,經過幾個小時的努力,我似乎還沒有弄明白。
如果有任何提示或意見,我們將不勝感激! 非常感謝。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "expressions.h"
typedef enum Operation {
FIRST = 1,
REST = 2,
CONS = 3,
} 操作。
union Data {
操作操作。
char *string。
};
struct Expression {
資料資料。
運算式 *leftArgument;
運算式 *rightArgument;
};
char* eval(Expression e) {
return "0"/span>;
}
運算式 *addNode(Expression *e, Expression *tree) {
if (tree == NULL) {
tree = malloc(sizeof(Expression))。
樹->資料=e->資料。
tree->leftArgument = NULL;
tree->rightArgument = NULL;
printf("added new node
")。)
} else if (tree->data.operation == FIRST || tree->data.operations == REST) {
printf("%d
", tree->data.operations)。
addNode(e, tree->leftArgument)。
}
return tree。
}
int main() {
運算式 *tree = NULL。
printf("----------[INSERT]-----------
")。)
運算式e1;
e1.data.operations = FIRST;
tree = addNode(&e1, tree)。
printf("-----------------------------
")。)
printf("----------[INSERT]-----------
")。)
運算式e2;
e2.data.operations = REST.Operation()
tree = addNode(&e2, tree)。
printf("-----------------------------
")。)
printf("----------[INSERT]-----------
")。)
運算式e3;
e3.data.operations = FIRST;
tree = addNode(&e3, tree)。
printf("-----------------------------
")。)
printf("----------[INSERT]-----------
")。)
運算式e4;
e4.data.operations = REST.Operation()
tree = addNode(&e4, tree)。
printf("-----------------------------
")。)
uj5u.com熱心網友回復:
在遞回函式的呼叫中
addNode(e, tree->leftArgument);
你正在丟棄包含樹的新根的回傳值。
你可能打算這樣寫:
tree>leftArgument = addNode(e, tree->leftArgument);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322455.html
標籤:
上一篇:在物件的陣列中搜索元素
下一篇:靜態庫是否與版本無關?
