C Programming: Linked Lists Tutorial
Advertisement
This C programming language tutorial explores different types of linked lists: singly linked lists, doubly linked lists, and circular linked lists.
Linked Lists
There are several variations of linked lists, including singly linked lists, doubly linked lists, and circular linked lists.
Example: Singly Linked List
Here’s an example demonstrating how to create a basic singly linked list structure in C:
struct listnode {
int data;
struct listnode *next;
};
struct listnode node2 = {20, NULL};
struct listnode node1 = {10, &node2};
struct listnode *head = &node1;
Printing a Linked List
One of the most fundamental operations you can perform on a linked list is printing its contents. Here’s how to do it:
struct listnode *lp;
for(lp = head; lp != NULL; lp = lp->next) {
printf("Node: %p data: %d Next Node: %p\n", lp, lp->data, lp->next);
}
Explanation:
This for
loop is a little different from what you might be used to. Instead of terminating based on a numerical counter, it terminates when lp
(our list pointer) becomes NULL
. This indicates that we’ve reached the end of the list. Also, instead of incrementing a counter (like i++
), we’re moving to the next node in the list using lp = lp->next
. This is the standard loop structure for iterating through linked lists.
Singly Linked Lists Explained
A singly linked list is a data structure where elements (nodes) are connected in a linear sequence, with each node pointing only to the next node in the list. Operations are typically performed in one direction (uni-directional).
Doubly Linked Lists Explained
A doubly linked list takes the concept a step further. It’s a bidirectional data structure where each node points to both the next node and the previous node in the list. This allows you to traverse the list in either direction.