我是一名学生,正在为项目使用cpp制作树形结构。该程序应该从输入中获取字符串并将其输入树中。该树由具有指向其下一个同级(称为同级)及其第一个子级(称为子级)的指针的每个节点组织。但是,当我尝试创建将成员递归添加到树中的函数时,该函数不起作用。所有neccisarry步骤均已完成,但由于某些原因未链接节点。请看一下我的代码,感谢您的阅读。
#include <iostream>
#include <string>
struct node{
char data;
node *sibling = nullptr;
node *child = nullptr;
};
struct node* newNode(char data, unsigned int m)
{
if(m!=0) {
struct node *node = (struct node *) malloc(sizeof(struct node));
// std::cout << "node write" << std::endl;
node->data = data;
node->sibling = newNode(124,m-1);
node->child = newNode(124,m-1);
return (node);
}
}
char TreeOutput(node *n){
return *(char *)n;
}
void nodeAdd(node *currentNode, std::string str, int m ){
int n = str.length();
if(m<n){
if(TreeOutput(currentNode) == str[m]){
std::cout << m << "1..1" << std::endl;
nodeAdd(currentNode->child,str,m+1);
}
else if(TreeOutput(currentNode) == 124){
std::cout << m << "2..2" << std::endl;
currentNode = newNode(str[m],2);
nodeAdd(currentNode->child,str,m+1);
}
else{
std::cout << m << "3..3" << std::endl;
nodeAdd(currentNode->sibling,str,m+1);
}
}
}
int main() {
struct node *root = newNode('X',6);
std::cout << root->data << std::endl;
nodeAdd(root->child,"APE",0);
std::cout << root << std::endl;
return 0;
}
答案 0 :(得分:0)
他们未在此行中链接的原因:
currentNode = newNode(str[m],2);
是因为您要为该函数添加一个节点*,然后为函数内的指针分配一个新值。因此,您可以在函数中更改currentNode的值,但不能在其父项中更改。您需要引用该指针或一个双指针才能使其正常工作:
void nodeAdd(node*& currentNode, std::string str, int m )
如果我们删除指针的语法糖,可能会更有意义。假设我们写了一个指向节点的指针Ptr<node>
:
void nodeAdd(Ptr<node> currentNode, std::string str, int m )
很明显,我们将 pointer 用作值,因此它现在位于函数中的变量中。如果我们将其作为参考,则可以在函数外部更改其值:
void nodeAdd(Ptr<node>& currentNode, std::string str, int m )
可能地,您在节点结构中有char数据,我想您也想要一个指针(或数组)。
就一般样式而言,如果您尝试编写C ++,通常newNode的内容将放入构造函数中,因此您只需编写new node(args...)
即可创建一个新实例。由于节点的布局简单,因此TreeOutput函数在这种情况下将起作用 ,但是一般来说,强制转换为struct的第一个成员是不必要的(特别是在继承或继承的情况下)虚拟方法),因此我至少要直接访问成员return node->data;