I already went to the tutorials and i have tried using google but i still don't completely understand the concept behind linked list...
from what I understand so far, a linked list consists of a pointer that points to the first node, and every node has a variable that contains a value and another pointer that points to the next node. The last node usually has a nullptr that indicates the end of the list.
Can someone give me a small example of a linked list and EXPLAIN what exactly is going on with each line of code?
There's no point in writing code if you don't understand the concept.
You correctly described a linked list.
The reason why it's important is that it doesn't require the user to know the size of the list before you start. You can simply keep adding/removing nodes throughout the lifetime of the program. You can't do that with array based data structures.
#include <iostream>
#include <string>
struct Node
{
Node(const std::string& name, int age) :
next(nullptr),
name(name),
age(age)
{
}
Node* next;
std::string name;
int age;
};
Node* head = NULL; // head of linked list
int main()
{
std::string name;
int age;
while (std::cin >> name >> age)
{
Node* node = new Node(name, age); // create a new node
if (head == nullptr)
{
head = node; // start list with new node
}
else
{
// traverse the linked list looking for the last node
Node* p = head;
while (p->next != nullptr)
{
p = p->next;
}
p->next = node; // append new node to end of list
}
}
}