Reputation: 157
I am trying to create a simple one way Linked List. I understand it conceptually but I'm stuck trying to create one. I know there are guides out there but I understand things better by trial and error.
My simple Contact
class:
class Contact
{
std::string name, phNum;
Contact* next;
public:
void getInfo();
void printInfo();
};
At this point, all I am trying to do is to create a list with some contacts (i.e. an address book of sorts), and then print out their information.
As per my understanding, the list should contain several unique objects of type Contact
.
My question is, how can I create multiple objects in the heap that have unique addresses? I tried the below, but it obviously didn't work as all the pointers will be identical.
while(true)
{
Contact* newEntry= new Contact;
newEntry->getInfo();
// rest of the linking stuff
}
Upvotes: 2
Views: 522
Reputation: 477
Okay just create a new contact and link it to the previous one. It looks like this conceptually.
object
|
Pointer to next one -> object
|
Pointer to next one -> object
Contact* newEntry= new Contact();
newEntry->getInfo();
newEntry->next = new Contact();
newEntry->next->getInfo();
newEntry->next->next = new Contact();
Upvotes: 1
Reputation: 1431
To initialize many contacts in a loop you may want to do something like this:
Contact *FirstOne = new Contact();
Contact *current = FirstOne;
while(...)
{
current->next = new Contact();
current = current->next;
//do stuff to current, like adding info
}
That way you are building up your Contact list. After that *FirstOne
ist the first and *current
is the last element of your list. Also you may want to make sure that the constructor sets *next to NULL to detect the end of the list.
Upvotes: 3