Reputation: 35
#include "PersonList.h"
#include <iostream>
#include <string>
using namespace std;
PersonList::PersonList()
{
head = NULL; //Head is a PersonRec*
}
struct PersonRec
{
string aName;
int aBribe;
PersonRec* link;
};
void PersonList::AddToList()
{
//string a;
//int b;
PersonRec* p;
PersonRec **currPtr = &head;
p = new PersonRec;
cout << "\nEnter the person's name: ";
cin >> p->aName;
cout<< "\nEnter the person's contribution: ";
cin >> p->aBribe;
if (head == NULL)
{
cout<<1<<endl;
head=p;
}
else if(head!=NULL)
{
bool x = true;
while (x != false)
{
*currPtr = (*currPtr)->link;
if (currPtr == NULL)
{
currPtr = &p;
x = false;
}
}
}
}
This is supposed to be a linked list in which a user inputs a name and a bribe amount and is added to the list with the highest amount of bribe being placed first.
In this particular stage I am just trying to figure out how to input people into the list more than once, without the bribes even coming into the equation. Because of the inclusion of pointers, which I am not so good at, I am having troubles here.
After the first node in the list is inputted successfully, the program freezes after I input the second node so my code at "else if(head!=NULL)" is flawed. I'm not sure if it's the syntax or I simply don't get the concept entirely.
Also, I am not allowed to use a link back to the previous node as part of the PersonRec structure, and that might have helped me.
How can I fix this problem?
Upvotes: 1
Views: 240
Reputation: 41232
You are getting close, but the code is not actually adding the new second item to the list. A problem with it is that it reaches the end of the list and the final assignment:
currPtr=&p;
simply assigns the address of the new list element to the local variable currPtr (that does not result in it being added to the list). The following are some suggestions towoard getting it working (this kind of seems like homework, so I don't want to just give the code):
p->link
to NULL after creating the object. It does not appear that there is a constructor that would initialize it (the mix of struct and class seems a bit odd in this situation).currPtr
.Upvotes: 2