通过引用传递指针(插入到二叉搜索树中)

Passing a pointer by reference (insert into binary search tree)

本文关键字:搜索树 插入 引用 指针      更新时间:2023-10-16

我的程序正在调用一个成员函数,该函数使用通过引用传递的指针执行插入到二叉搜索树中(以便更改指针的值(。 但是,当我尝试将第二个节点插入树中时,程序崩溃了。 我假设这与一个糟糕的指针有关。

此赋值中唯一可以更改的部分是成员函数的实现,而不是声明。

任何帮助将不胜感激。

 //Header file
using namespace std;
struct PersonRec
{
    char name[20];
    int bribe;
    PersonRec* leftLink;
    PersonRec* rightLink;
};

class CTree
{
private:
    PersonRec *tree;
    bool IsEmpty();
    void AddItem( PersonRec*&, PersonRec*);
    void DisplayTree(PersonRec*);
public:
    CTree();
    //~CTree();
    void Add();
    void View();
};
//Implementation file
#include <iostream>
#include <string>
using namespace std;
#include "ctree.h"
CTree::CTree()
{
    tree = NULL;
}
//PersonList::~MyTree()
//{
//
//}

bool CTree::IsEmpty()
{
    if(tree == NULL) 
    {
        return true;
    }
    else
    {
        return false;
    }
}
void CTree::Add()
{
    PersonRec* newPerson = new PersonRec();
    cout << "Enter the person's name: ";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    cin.getline(newPerson->name, 20);
    cout << "Enter the person's contribution: ";
    cin >> newPerson->bribe;

    newPerson->leftLink = NULL;
    newPerson->rightLink = NULL;
    AddItem(tree, newPerson);
}
void CTree::View()
{
    if (IsEmpty())
    {
        cout<<"The list is empy";
    }
    else
    {
        DisplayTree(tree);
    }
};
void CTree::AddItem( PersonRec*& ptr, PersonRec* newPer )
{
        if (tree == NULL)
        {
            ptr = newPer;
        }
        else if ( newPer->bribe < ptr->bribe)
            AddItem(ptr->leftLink, newPer); 
        else
            AddItem(ptr->rightLink, newPer); 
}
void CTree::DisplayTree(PersonRec* ptr)
{
    if (ptr == NULL)
                    return;
    DisplayTree(ptr->rightLink);
    cout<<ptr->name<<" "<<"$"<<ptr->bribe <<endl;
    DisplayTree(ptr->leftLink); 
}

//Driver file
#include <iostream>
using namespace std;
#include <cstdlib>
#include "ctree.h"
int displayMenu (void);
void processChoice(int, CTree&);
int main (void)
{
int num;
CTree ct;
do 
{
num = displayMenu();
if (num != 3)
processChoice(num, ct);
} while (num != 3);
return 0;
}
int displayMenu (void)
{
int choice;
cout << "nMenun";
cout << "==============================nn";
cout << "1. Add student to waiting listn";
cout << "2. View waiting listn";
cout << "3. Exit programnn";
cout << "Please enter choice: ";
cin >> choice;
return choice;
}
void processChoice(int choice, CTree& myTree)
{
   switch (choice)
   {
      case 1: myTree.Add (); break;
      case 2: myTree.View (); break;
   } 
}

CTree::AddItem 中,您的条件是错误的:

    if (tree == NULL)
    {
        ptr = newPer;
    }

应该是

    if (ptr == NULL)
    {
        ptr = newPer;
    }

当你调用AddItem(ptr->rightLink, newPer); 时,newPer是新节点,但当前根的任何一个后代都可以NULL,所以这是你需要检查NULL和替换的,而不是新节点。