I'm currently learning Linked Lists in C++, and I can't write a print function which prints out the elements of the list; I mean I wrote the function but it doesn't work properly.
#include <iostream>
using namespace std;
struct node
{
char name[20];
node* next;
};
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
int main()
{
node* head = NULL;
node* temp = head;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for (unsigned short i = 1; i <= people; i++)
{
addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
while (temp != NULL)
{
printList(temp);
temp = temp->next;
}
cin.get();
}
I am wondering what I'm doing wrong, please help me!
Best Answer
It is obvious that function addNewPerson is wrong.
You allocated new node person.
Set its field next to NULL
Then if head is not equal to NULL you set person to person->next
As person->next was set to NULL it means that now also person will be equal to NULL.
Moreover the function returns head that can be changed in the function. However you ignore returned value in main
At least there should be
The valid function addNewPerson could look the following way
And in main you have to write
Function printList does not output the whole list. It outputs only data member name of the first node that is of head.
It should look the following way
And at last main should look as