gpt4 book ai didi

c++ - 将节点插入二叉搜索树/链表?

转载 作者:行者123 更新时间:2023-11-28 00:59:13 24 4
gpt4 key购买 nike

好吧,我对这个问题已经筋疲力尽了,所以我想我会得到一些外部帮助。该程序拥有一个人员“数据库”,其中包括员工和学生。每个学生都有一个“书籍”的二叉树,用户可以插入和搜索。我需要输入一个学生的姓名,找到与该学生相对应的 Personnel 节点,然后将一本书添加到该学生的 bookTree 中。

我得到的错误信息是“Homework4.exe 中 0x013c53a0 处的未处理异常:0xC0000005:访问冲突读取位置 0xcccccd1c。”,我认为这意味着我在某处弄乱了指针。调用堆栈将第 512 行(以及 book_traverse() )显示为问题制造者。这是我目前所拥有的(省略不必要的代码):提前致谢!

class PersonnelNode {       // This is a container class
private:
Personnel *pNode; // It contains a Personnel class
PersonnelNode *pNext; // pointer used to form a linked list
public:
void setNode(Personnel *pNode) { this->pNode = pNode; }
void setNext(PersonnelNode *pNext) { this->pNext = pNext; }
Personnel* getNode() { return pNode; }
PersonnelNode* getNext() { return pNext; }

PersonnelNode() { // constructor
pNode = NULL;
pNext = NULL;
}
} *head = NULL; // declare a global pointer variable head

....

struct Book {
char title[75];
char url[75];
char key;
Book *left;
Book *right;

Book(char *title, char *url) { // Constructor
strcpy_s(this->title, title);
strcpy_s(this->url, url);
key = title[0];
left = NULL;
right = NULL;
}
};

....

class Student : public Personnel { //inherit from Personnel
... (omitted the unnecessary code)
Book *bookTree;


//BookTree = NULL in constructor
}

....

int insert_book() {
PersonnelNode *temp, *prev;
Personnel *person;
Student *student;
Book *newBook;
char title[75], url[75], sName[75];
temp = head;

cout << endl << "@Inserting book node.........." << endl;
cout << "Enter the student name: ";
cin.ignore();
cin.getline(sName, 75);
//*****My error is probably below here?
while (temp != NULL) {
person = temp->getNode();
if (sName != person->getName()) {
prev = temp;
temp = temp->getNext();
}
else {
student = (Student *) person;
}
}
cout << "Enter the book title: ";
cin.getline(title, 75);
cout << "Enter the URL: ";
cin.getline(url, 75);
newBook = new Book(title, url);
book_traverse(student->bookTree, newBook); //LINE 512
return 0;
}

....

//***Recursive function to insert book
void book_traverse(Book* root, Book* newBook) { //Is this right?
if (root == NULL) //I tried Book* &root, but then
root = newBook; //the compiler doesn't like root==NULL
else if (newBook->key < root->key)
book_traverse(root->left, newBook);
else
book_traverse(root->right, newBook);
}

最佳答案

我想你需要书**

void book_traverse(Book** root, Book* newBook) 

然后在任何地方都使用 *root 而不是 root,例如

*root = newBook

否则在 book_traverse 中,您正在更改 root 的本地拷贝。

关于c++ - 将节点插入二叉搜索树/链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9654676/

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