-2
#include <string>

using namespace std;

class PersonList
{

private:
    char aName[7];
    int aBribe;
    PersonList *link;

public:
    void addNodes();
    void display();

};

#include <iostream>
#include <string>

using namespace std;

#include "mylink.h"

void PersonList::addNodes()
{

    PersonList *temp2;

    PersonList* startPtr = new PersonList();
    PersonList* current = new PersonList();


        PersonList *temp = new PersonList();//created the first node on the list
        cout<<"Enter the person's name: ";
        cin>>temp->aName;
        cout<<"Enter the person's contribution: ";
        cin>>temp->aBribe;
        temp->link=NULL;//when i get last node, link will point to null(where am i in list?)

        if(startPtr==NULL)
        {
            startPtr = temp;
            current = startPtr;
        }

        else
        {
            temp2 = startPtr;

            while(temp2->link!=NULL)
                temp2 = temp2->link;
            temp2->link=temp;
        }
    //}
}

void PersonList::display()
{
    PersonList *temp;
    PersonList *startPtr = this;

    temp=startPtr;

    while(temp != NULL)
    {
        cout<<temp->aName<<"\t\t"<<temp->aBribe<<endl;
        temp = temp->link;
    }

}

#include <iostream>
#include "mylink.h"

using namespace std;

int displayMenu (void);
void processChoice(int, PersonList&);

int main()
{
int num;

PersonList myList;


do 
{
num = displayMenu();
if (num != 3)
processChoice(num, myList);
} 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;

cin.ignore();
return choice;
}

void processChoice(int choice, PersonList& p)
{

switch(choice)
{
case 1: p.addNodes();
break;
case 2: p.display();
break;
}

}

我的问题是显示功能不显示我输入的名称和贡献。我使用临时变量作为指针节点来调用 aName 和 aBribe。当它没有达到空值时,它会遍历列表。输出中没有显示

4

1 回答 1

4

您正在创建一个新列表:

PersonList *startPtr = new PersonList();

然后展示出来。所以,自然是空的。

您的 addNodes 方法中有类似的问题。您正在将节点添加到新列表中,然后将其丢弃,这实际上是内存泄漏。

于 2012-05-06T17:53:55.617 回答