2012-05-18 2 views
2

Моя программа вызывает функцию-член, которая выполняет вставку в двоичное дерево поиска с указателем, переданным по ссылке (так, чтобы значение указателя было изменено). Однако, когда я пытаюсь вставить второй узел в дерево, программа сработает. Я предполагаю, что это связано с плохим указателем.Передача указателя по ссылке (вставка в двоичное дерево поиска)

Единственная часть этого задания, которую можно изменить, это реализация функций-членов, а не декларация.

Любая помощь будет оценена по достоинству.

//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 << "\nMenu\n"; 
cout << "==============================\n\n"; 
cout << "1. Add student to waiting list\n"; 
cout << "2. View waiting list\n"; 
cout << "3. Exit program\n\n"; 
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; 
    } 
} 

ответ

2

В CTree::AddItem, ваше состояние является неправильным:

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

должен быть

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

Когда вы звоните AddItem(ptr->rightLink, newPer);, newPer это новый узел, но либо из потомков тока root может быть NULL, так что вам нужно проверить для NULL и заменить, а не новый узел.

+0

Спасибо, я не могу поверить, что не понял этого. Я потратил несколько часов на это :) ty – Zzz

+0

@ Ацци рада помочь! –

Смежные вопросы