0
我在做家庭作業時遇到問題。我完成了大部分工作,但我被困在這一部分。如果你看看頭文件,你會看到一條評論:我需要將節點對象轉換爲C中的字符串
將節點對象轉換爲字符串。我們需要一個指向節點對象的指針,以便我們可以顯示對象的地址以供進一步參考。
我盡我所能,但我不知道該從哪裏出發。
The output from this test program looks like:
<0x0022ff40>[value: 2, left: 0x00000000, right: 0x00000000]
<0x0022ff30>[value: 3, left: 0x00000000, right: 0x00000000]
<0x0022ff20>[value: 4, left: 0x00000000, right: 0x00000000]
<0x0022ff10>[value: *, left: 0x0022ff30, right: 0x0022ff20]
<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff10]
Tree evaluation: 14
<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
Tree evaluation: 20
<0x0022ff00>[value: ., left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
invalid operator: .
這是我main()
:
#include <stdio.h>
#include "TreeNode.h"
int main(void)
{
Node n2, n3, n4, times, plus;
setNode(&n2, 2, NULL, NULL, true);
setNode(&n3, 3, NULL, NULL, true);
setNode(&n4, 4, NULL, NULL, true);
printf("\n");
setNode(×, '*', &n3, &n4, true);
setNode(&plus, '+', &n2, ×, true);
printf(" Tree evaluation: %d\n\n", eval(&plus));
setNode(&plus, '+', &n2, &n3, true);
setNode(×, '*', &plus, &n4, true);
printf(" Tree evaluation: %d\n\n", eval(×));
setNode(&plus, '.', &n2, &n3, true);
setNode(×, '*', &plus, &n4, true);
printf(" Tree evaluation: %d\n\n", eval(×));
return 0;
}
這是我的頭:
#include <stdio.h>
#ifndef TREE_NODE
#define TREE_NODE
typedef struct Node_t {
int value;
struct Node_t *left;
struct Node_t *right;
} Node, *Node_p;
typedef char* String;
typedef enum {false, true} bool;
/*
* Convert a Node object to a string.
*
* We require a pointer to the Node object so that we can display the
* address of the object for further reference.
*/
String nodeToString(Node_p np) {
static char output[0];
sprintf(output, "<0x%d>\n", np, np->value, np->left, np->right);
return output;
}
void setNode(Node_p np,
int value,
Node_p left,
Node_p right,
bool display) {
np->value = value;
np->left = left;
np->right = right;
if (display) {
printf("%s\n", nodeToString(np));
}
}
int eval(Node_p np){
switch(np->value) {
case '+':
np->value = eval(np->left) + eval(np->right);
return np->value;
case '-':
np->value = eval(np->left) - eval(np->right);
return np->value;
case '*':
np->value = eval(np->left) * eval(np->right);
return np->value;
case '/':
np->value = eval(np->left)/eval(np->right);
return np->value;
default:
exit(1);
}
return 0;
}
#endif
錯誤'nodeToString'。並在評估:除了運營商時退出。 – BLUEPIXY
我認爲有必要提供一個用於區分的字段我們不能在當前結構中區分運營商和號碼, – BLUEPIXY
或校驗節點有孩子。 – BLUEPIXY