Linked Lists in C
In questa pagina 9
Why lists
C has no built-in list: it is built from struct + pointers + malloc (<stdlib.h>: malloc/calloc/realloc/free). See Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C → and Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C → for the memory model (static, automatic, dynamic = heap).
A list is a finite succession of elements of one type. What it encodes is the values and their order. A list is defined also by its operations: insertion/deletion (head, tail, middle), visit/search, initialization.
Different insert/delete rules give different lists:
- stack: LIFO (last in, first out)
- queue: FIFO (first in, first out)
Representations:
- sequential: elements in an array, order implicit in the position
- linked: order explicit, each element knows its successor (index or pointer). A pointer-linked list is a sequence of nodes connected by pointers.
Linked list vs array
| Array | Linked list | |
|---|---|---|
| Size | fixed beforehand (worst case), can fill up | grows/shrinks at run time |
| Memory | contiguous | nodes at non-contiguous addresses, "logically" in sequence |
| Access | immediate (index) | sequential only, from the head |
| Insert/delete | slow (shift elements) | pointer manipulation only |
| Combine two lists | may not fit either array | modify one pointer |
| Memory cost | no pointers | one extra pointer per node |
Array drawbacks listed: adding when there is no more room; deleting means moving data (or marking the slot with a special value); combining needs room for the sum of sizes. A linked list allocates a node only when needed (usually on a user request): create a template for any element, malloc as needed, add a pointer member, link each new allocation to the previous ones.
Node and list
The node is a self-referential struct:
struct Node {
int data;
struct Node* next;
};data: value of the node;next: pointer to the following node.- The head pointer tracks the start of the list; the last node's
nextisNULL. - Example list {3, 5, ..., 19}:
list -> [3|next] -> [5|next] -> ... -> [19|NULL].
Initialization of an empty list:
struct Node* myList = NULL;Creating a node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
}
else {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}Use (always check the result of malloc):
int main()
{
struct Node *list = NULL;
struct Node *newNode = NULL;
// ...
if ((newNode = createNode(17)) != NULL)
{
//...
}
// ...
}Insertion
At the head
Steps: allocate, set the data, link the new node to the current head, make it the new head.
Version with a pointer to the head pointer (the function modifies list of the caller):
void head_insert(struct Node **ptr, struct Node *newNode)
{
struct Node *tmp;
tmp = *ptr;
*ptr = newNode;
(*ptr)->next = tmp;
}Version returning the new head (list = head_insert(list, n);):
struct Node* head_insert(struct Node *head, struct Node *newNode)
{
newNode->next = head;
return(newNode); //new head
}At the tail
void tail_insert(struct Node **ptr, struct Node *newNode)
{
struct Node *tmp;
tmp = *ptr;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = newNode;
if (*ptr==NULL)
*ptr = newNode;
}Careful: as written on the slide, tmp->next is read before the *ptr == NULL check, so it fails on an empty list (tmp is NULL). The empty-list test must come first (if (*ptr == NULL) *ptr = newNode; else { walk; link }). The extracted slide text also lists the lines in a scrambled order.
After a given item
unsigned int insertItem(struct Node *head, int itemToInsAfter, struct Node *toBeInserted)
{
struct Node *tmp;
while ((head != NULL) && (head->data != itemToInsAfter))
head = head->next;
if (head->data== itemToInsAfter)
{
tmp = head->next;
head->next = toBeInserted;
toBeInserted->next = tmp;
return(0); // item inserted
}
else
return(1);
}Returns 0 if inserted, 1 otherwise. Same flaw: when the value is not found head is NULL and head->data is dereferenced.
Ordered insertion
An ordered list keeps elements sorted on a key field (ascending or descending, via a comparison). It is not a C data structure: it is a list (or array) where insertion is done in the right place. Same list as before except insertion depends on the key.
struct Node* insertInOrder(struct Node* head, struct Node *newNode) {
// If the list is empty or the new node should be inserted at the beginning
if (head == NULL || newNode->data < head->data) {
newNode->next = head;
return newNode;
}
// Traverse the list to find the correct position for the new node
struct Node* current = head;
while (current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
// Insert the node in the correct position
newNode->next = current->next;
current->next = newNode;
return head;
}The loop stops on the node before the insertion point (it looks at current->next), so the new node can be linked in both directions.
Search and traversal
struct Node * searchItem(struct Node *head, int itemToSearch)
{
while ((head != NULL) && (head->data != itemToSearch))
head = head->next;
return(head); // NULL if not found
}The order of the two tests matters: head != NULL first (short-circuit), then head->data.
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}Deletion
Steps: locate the target, update the previous node's next to bypass it, free the node (avoid memory leaks). Three versions appear on the slides.
1. Head passed by value (cannot remove the head, since the caller's pointer cannot change):
unsigned int deleteItem(struct Node *head, int itemToDelete)
{
struct Node *prev = head;
while ((head != NULL) && (head->data != itemToDelete))
{
prev = head;
head = head->next;
}
if (head->data==itemToDelete)
{
prev->next = head->next;
free(head);
return(0); // item deleted
}
else
return(1);
}2. Pointer to the head pointer (handles the head: *ptr is updated). The slide shows the code split in two pieces (the middle part is cut with "..."):
unsigned int deleteItem(struct Node **ptr, int itemToDelete)
{
struct Node *current = *ptr;
struct Node *prev = current;
while ((current != NULL) && (current->data != itemToDelete))
{
prev = current;
current = current->next;
}
if (current->data == itemToDelete)
{
if (current != *ptr)
{
prev->next = current->next;
}
else
{
*ptr = current->next;
}
free(current);
return(0); // item deleted
}
else
return(1);
}3. Returning the new head (handles head and not-found case without dereferencing NULL):
struct Node* deleteByValue(struct Node* head, int key) {
struct Node* temp = head;
struct Node* prev = NULL;
// If the head node itself holds the key
if (temp != NULL && temp->data == key) {
head = temp->next; // Change head
free(temp); // Free old head
return head;
}
// Search for the key
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If the key was not present
if (temp == NULL) return head;
prev->next = temp->next; // Unlink the node
free(temp); // Free memory
return head;
}Versions 1 and 2 read ->data after a loop that can end with the pointer NULL (item absent): version 3 is the safe one.
Exercises (slides, statements only)
Trace: starting from an empty list, execute insert_head(5), insert_head(3), insert_tail(7), insert_after(value=3, new=4), delete_value(5). Working it out: 5 -> 3 5 -> 3 5 7 -> 3 4 5 7 -> 3 4 7.
Implement:
struct Node* reverse_list(struct Node* head);struct Node* middle_node(struct Node* head);struct Node* remove_n_from_end(struct Node* head, int n);struct Node* merge_sorted(struct Node* a, struct Node* b);(no new allocations: relink existing nodes)void remove_dups_sorted(struct Node* head);
The slides give no solutions for these. Sorting techniques for lists are in Sorting Linked ListsA linked list can be sorted with bubble, insertion, quick or merge sort by relinking nodes instead of copying data; merge sort with a slow/fast split is the cleanest on lists.Sorting Linked Lists →; list applications as exercises in Lab Exercises - Lists, Arrays and TreesLab problem sets on linked lists, stacks, queues, arrays and binary search trees, with the statements, the data declarations and program skeletons given on the slides, plus the quiz questions.Lab Exercises - Lists, Arrays and Trees →.
Other kinds of lists
The list above is a one-way (singly) list: better than arrays when there are many insertions/deletions, fairly simple to manage. Deficiency: cannot visit an element from another one; some problems need extra pointers.
| Type | Structure | Notes |
|---|---|---|
| Singly linked | data + next |
one-way traversal |
| Doubly linked (two-way) | pointer to previous + data + pointer to next | first node's prev and last node's next are NULL; two visit routines (forward, backward); cuts access time, simplifies delete/insert without full traversal; e.g. "print from 20 to 50", "print 16 and preceding 4"; often also circular; e.g. an editor with a linked list of lines |
| Circular | last node points back to the first | no first element and no end; there is a current element = starting point of the next operation; used heavily in memory management schemes, round-robin scheduling, buffering |
| Nested (network) | each element holds the head pointer of another list | e.g. flights (departure city, flight number, destination city, pointer to next flight, pointer to passengers, count) each with a linked log of passengers; words of a file with the linked line numbers (cross reference) |
The element of a list is usually a structure (passenger: name, flight number, seat; OS job: owner, priority, files; window: coordinates). Lists hold (usually) like objects, are dynamic (no upper size), common operations: add, insert, delete, print, combine two lists.
Pros and cons
- Dynamic sizing, no reallocation.
- Efficient insertions and deletions: no shifting.
- Higher memory usage (a pointer per node).
- Sequential access only.
Versione ripasso
- A list is a chain of nodes built with
struct+ pointers +malloc(<stdlib.h>), see Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C → and Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →. It encodes the values and their order. Different insert and delete rules give stacks (LIFO) and queues (FIFO) (Stacks and Queues in CA stack is LIFO (push/pop at the top), a queue is FIFO (enqueue at the rear, dequeue at the front); both can be built on an array or on a linked list, all operations in constant time.Stacks and Queues in C →). - Node: a self-referential struct
struct Node { int data; struct Node* next; };. The head pointer marks the start, the lastnextisNULL, an empty list isstruct Node* myList = NULL;. - Array versus list: an array is contiguous with a fixed size and instant access by index, and moving elements makes insert and delete slow. A list grows and shrinks at run time, insert and delete only relink pointers, access is sequential only, and each node pays for one extra pointer.
createNode(value):malloc(sizeof(struct Node)), check the result forNULL, then setdataandnext = NULL.- Head insert:
newNode->next = head;then the new node becomes the head. Version 1 takesstruct Node **ptrand updates*ptr; version 2 returns the new head (list = head_insert(list, n);). - Tail insert: walk with
while (tmp->next != NULL)to the last node, then link. The empty-list testif (*ptr == NULL)must come first: the slide's order readstmp->nexton aNULLpointer. - Insert after a given value: walk while
head != NULL && head->data != item, thentmp = head->next; head->next = new; new->next = tmp;. Return 0 if inserted, 1 otherwise; check forNULLbefore readinghead->data. - Ordered insert (ascending key): if the list is empty or the new value is smaller than the head, the new node becomes the head. Otherwise walk while
current->next != NULL && current->next->data < newNode->data, so the loop stops on the node before the position, thennewNode->next = current->next; current->next = newNode;. - Search and visit:
while (p != NULL && p->data != x) p = p->next;. TheNULLtest comes first (short-circuit).printListwalks withcurrentand printscurrent->data. - Delete: find the node and its predecessor
prev, setprev->next = cur->next, thenfree(cur). Three versions on the slides: (1) head passed by value, which cannot delete the head; (2)struct Node **ptr, which handles the head by updating*ptr; (3) return the new head, the safe one, which also handles a key not found. Versions 1 and 2 dereferenceNULLwhen the item is absent. - Trace of the exercise: empty list,
insert_head(5),insert_head(3),insert_tail(7),insert_after(3, 4),delete_value(5)gives3 4 7. - Exercises (no solutions on the slides): reverse the list, middle node, remove the n-th from the end, merge two sorted lists by relinking without new allocations, remove duplicates from a sorted list (Liste concatenateLista concatenata semplice: nodi allocati dinamicamente collegati da puntatori; inserimento e rimozione in testa, scorrimento, ricerca, inserimento ordinato, deallocazione; confronto dei costi con l'array; versione in Python.Liste concatenate →). Sorting lists: Sorting Linked ListsA linked list can be sorted with bubble, insertion, quick or merge sort by relinking nodes instead of copying data; merge sort with a slow/fast split is the cleanest on lists.Sorting Linked Lists →.
- Other lists: doubly linked (
prevandnext, two visit routines, faster delete and insert, firstprevand lastnextareNULL); circular (last points to first, has a current element, used in round-robin scheduling and buffering); nested (each element holds the head of another list, e.g. flights with a list of passengers). - Typical errors: dereferencing
NULLafter a failed search, deleting the head with a by-value head pointer, forgettingfree, empty-list case in tail insertion, reading->dataafter the loop ran past the end.