2012-05-06 70 views
-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。當它沒有達到空值時,這將通過列表。沒有任何顯示輸出鏈接列表C++,輸出不顯示在顯示功能

+1

當你構造一個新的PersonList時會發生什麼?它調用'addNodes()'addNodes似乎只在本地實例上工作,而不是傳遞給變量或本身,這是打算? – EdChum

回答

4

您正在創建一個新的列表:

PersonList *startPtr = new PersonList(); 

,然後表示。所以,它自然是空的。

你的addNodes方法有類似的問題。您將節點添加到新列表中,然後將其丟棄,這實際上是內存泄漏。

+0

感謝您的快速響應。我現在把這個PersonList * startPtr;它說它startPtr正在被使用而不被初始化。問題是什麼? – Masoman

+0

很難確定沒有看到你的類定義,但也許你想PersonList * startPtr = this; –

+0

這是我的班級定義#include using namespace std; class PersonList { private: \t char aName [7]; \t int aBribe; \t PersonList * votePtr; public: \t void addNodes(); \t void display(); }; – Masoman