Let me ask you: what is "next" in this code? It's not defined.
"next" typically refers to the next element of the list. it's a pointer, that will be necessary for things like traversing the list and creating new elements of the list.
I know creating a linked-list is one of those re-inventing the wheel type problems you're faced with in school, but an understanding of how a linked-list works is a must if you wish to continue your journey.
First ask, what am i creating a list of? people? sure, let's create a linked-list of people.
Code:
#include <iostream>
using namespace std;
class Person{
public:
// Notice "next(0)"...
// next is set to zero or NULL so we know where the end of our list is.
Person(string n, string o, int a) : name(n), occupation(o), age(a), next(0) {};
string get_name(){ return name; };
string get_occupation(){ return occupation; };
int get_age(){ return age; };
// Because next is private, we can access it like so:
Person * get_next(){ return next; };
// And if we'd like to create new Persons, let's add this:
void add_person(string n, string o, int a){ next = new Person(n,o,a); };
private:
string name;
string occupation;
int age;
// This will allow us to make our list:
Person * next;
};
int main(){
// Let's declare a Person pointer "head" here that will be the first person in our list.
Person * head;
// Right now, no Person exists, so let's actually create the first Person like this:
head = new Person("Bob", "Programmer", 35);
// Now let's create another person
// We'll need another "general purpose" pointer:
Person * p = head;
// With our add_person() function, a new person will be created in the next position:
p->add_person("Alice", "HairDresser", 26);
// But what if we don't always want to create a new Person? What if we need to do that later?
// We can always get to the last person our list with a loop like this:
p = head;
while(p->get_next() != 0) // 0 indicates the end of the list
{
p = p->get_next();
}
// Now let's go ahead and add one more person:
p->add_person("Jerry", "BarTender", 28);
// To display our list in the command window:
// Initialize p back to the beginning:
p = head;
// Traverse the list showing the different people:
while(p != 0){
cout << p->get_name() << " " << p->get_occupation() << " " << p->get_age() << endl;
// Advance p to the next person until we get to the end:
p = p->get_next();
}
return 0;
}
This is by no means a complete tutorial on linked lists, in-fact, this list I've created here is not very practical for many reasons. But it does illustrate some of the aspects of creating a linked-list.
Try creating your own lists of things, and remember pointers only POINT. that's all they do. study this, and other data structures.