Can someone help me completely understand the concept behind linked lists?

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.

Got it?

Anyway, here's some code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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
        }
    }
}
Ah thank you! Your code is so much more simple that the one in the tutorials
These are great also to help visualize what is happening in different data structures.
http://www.ic.unicamp.br/~rezende/Astral.htm
By the way: it's a singly linked list.

Doubly linked lists are more common:
http://en.wikipedia.org/wiki/Doubly_linked_list
http://www.cplusplus.com/reference/list/list/?kw=list
Topic archived. No new replies allowed.