A linked list print problem

Hi,
I implemented a linked list saves person data but when i print the list, it prints only the last element and it because i don't find where do I have to save a pointer to the beginning of the list. Any idea?
Thanks,
here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>
#include<string>

using namespace std;

class PersonData
{
    public:
	string name;
	int id;
	PersonData *next;

	PersonData()
	{
       name="";
       id=0;
	   next=NULL;
		
	}

};



class PersonList
{
    public:
	PersonData *list;
    PersonData *beginOfList;
   
	PersonList()
	{
		list=NULL;
		beginOfList=list;

	}

	void addPersonToList()
	{
		
		list=new PersonData();
		
		beginOfList=list;
		cout<<"list address="<<list<<"\n";
		cout<<"beginOfList address="<<beginOfList<<"\n";
		cout<<"Please enter the name of the person\n";
		cin>>list->name;
		cout<<"Please enter the id of the person\n";
		cin>>list->id;
		list->next=NULL;
		list=list->next;
		
		
	}
	
	void printList()
	{
		while(beginOfList!=NULL)
		{
			cout<<"name="<<beginOfList->name<<endl;
			cout<<"id="<<beginOfList->id<<endl;
			beginOfList=beginOfList->next;
		}
	}
};

int main()
{
	PersonList *h=new PersonList;
	h->addPersonToList();
	h->addPersonToList();
	h->printList();
    return 0;	
}                                                                                                                                                                                                                                                   
Last edited on
Last edited on
Topic archived. No new replies allowed.