gpt4 book ai didi

c++ - 在c中的多级双向链表中添加一个节点

转载 作者:行者123 更新时间:2023-11-30 17:47:30 25 4
gpt4 key购买 nike

我正在创建一个多级双向链接列表,我正在其中执行添加节点操作。我很困惑,因为根据下面提到的我的逻辑代码,它应该打印该值,但它没有打印。输出没有错误,但也许我做错了什么,这可能会影响压平该列表。

这个列表我有 3 个级别。 addNode 函数将在第一级添加节点,而 addChild 函数将在第二级或第三级的任意位置添加节点。

代码是:

Student* StudentList::addNode(int num)
{
Student* node = new Student(num);
if(head == 0) {
head = node;
tail = node;
} else {
node->prev = tail;
tail->next = node;
tail = tail->next;
}

return node;
}

添加 child :

Student* StudentList::addChild(Student* node1, int num)
{
Student* node = head;
Student* temp;
Student* temp1;

// traversing the list to find exact location
while(node != 0)
{
if(node->num == node1->num) {
break;
} else {
temp = node->child;
while(temp)
{
if(temp->num == node1->num) {
node = temp;
break;
} else {
temp1 = temp->child;
while(temp1)
{
if(temp1->num == node1->num) {
node = temp1;
break;
} else {
temp1 = temp1->next;
}
}
temp = temp->next;
}
}
node = node->next;
}
}

Student* newChild = new Student(num);
Student* curr = node->child;
if(curr == 0)
{
node->child = newChild;
} else {
while(curr->next)
{
curr = curr->next;
}
newChild->prev = curr;
curr->next = newChild;
}
return node1;
}

主要方法代码为:

StudentList* sl = new StudentList();
Student* newNode;
Student* newNode1;

newNode = sl->addNode(1);
newNode1 = sl->addChild(newNode,11);
sl->addChild(newNode1, 111);
sl->addChild(newNode1, 112);
newNode1 = sl->addChild(newNode,12);
newNode = sl->addNode(2);
newNode1 = sl->addChild(newNode,21);
newNode1 = sl->addChild(newNode,22);
sl->addChild(newNode1, 221);
sl->addChild(newNode1, 222);
sl->addChild(newNode1, 223);
newNode = sl->addNode(3);
newNode = sl->addNode(4);
newNode1 = sl->addChild(newNode,41);
sl->addChild(newNode1, 411);

sl->printList();

我的打印列表代码是:

void StudentList::printList(){
Student* curr = head;
while(curr){
cout<< *curr <<endl;
if(curr->child){
Student* newCurr = curr->child;
while(newCurr){
cout<< "*{"<<newCurr->num <<"}"<<endl;
if(newCurr->child){
Student* newCurr2 = newCurr->child;
while(newCurr2){
//according to my login this 3rd level childs num(id) value
//should be printed used only for 2nd level according to my
//logic.. where is the problem am i doing wrong any thing?
cout<< "**{"<<newCurr2->num <<"}"<<endl;
newCurr2 = newCurr2->next;
}
}
newCurr = newCurr->next;
}
}
curr = curr->next;
}

}

请帮助我,提前感谢大家。

最佳答案

从您在评论中输入的输出来看,第二级似乎没有添加任何内容。当您期望在第二级添加节点时,它们将被添加到第一级。

我认为问题出在添加子函数的底部:

Student* StudentList::addChild(Student* node1, int num)
{
// rest of function. node1 is never modified
return node1;
}

您始终将节点输入返回到该函数。我认为在您的以下代码中

newNode = sl->addNode(1);
newNode1 = sl->addChild(newNode,11);
sl->addChild(newNode1, 111);
sl->addChild(newNode1, 112);

您会发现 newNode1 == nodeNode 而不是我认为您所期望的子节点。也许添加子函数应该返回 newChild

关于c++ - 在c中的多级双向链表中添加一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com