New C tutorial on implementing linked lists with pointers
Once you leave the relative safety of arrays and structs, the linked list using pointers is probably the next thing to consider. Technically it’s a liked list of structs containing pointers. It’s like an array of structs only instead of allocating contiguous memory for an array, you allocate memory for each struct as you need it.
Linked lists are easy to program. You have a head pointer (a pointer to the head of the list). It starts as null as the list is empty. There’s two types of linked lists (single and double). A single list has a pointer to the next node (or is 0 at the end of the list) and can only be processed from head to end. A node is just a fancy name for the struct in the linked list.
A double list has two pointers. One to the previous node and one to the next. As well as a head pointer you need a tail pointer and you can process the list from head to tail or tail to head (i.e. backwards).
Now the first operation you can do on a linked list is add a node to it.
To do this you
- Allocate memory for the node using malloc.
- Copy the head pointer to the node’s next pointer.
- Stitch the node in by pointing the head pointer to this node.
So when you are building a list you add each node to the head, in a sense pushing it in front of the others.
Double linked lists have to do an additional operation which is set the next node’s previous pointer to point to the newly added pointer. And when you add the first node to a double linked list, you have to set the tail pointer to point to this first node. After that it never changes unless you have an Append node at the end.
Uses of Linked Lists
Anything that needs dynamic memory for example a text editor might use a double linked list to store all the text. Each line could be a different length. So each node would not only have a pointer to the next and previous nodes, it would have a pointer to the text in memory. When you insert a new line, you are just inserting a new node in the list at the current node that the cursor is on.
Or you might store a directed graph (a bit like in the picture) where each node has multiple pointers to other nodes. Anyway I’ve published tutorial eight which looks at pointers and linked lists.