Sub topic 15
Structs and singly linked lists
This chapter assumes you know pointer declaration and dereferencing, malloc and free, and how arguments are passed by value. It builds the linked list, the data structure GATE questions most often use to test those skills.
Structs: grouping fields
A struct groups named fields of different types into one object. Its fields are stored in declaration order, and a pointer to a struct is also a pointer to its first field.
Use . on a struct variable and -> on a pointer to a struct. The expression p->x means (*p).x.
Padding and alignment
The compiler may insert unused bytes (padding) between fields so that each field sits at an address that suits its type. It may also pad the end of the struct so that arrays of the struct stay aligned. The total size can therefore exceed the sum of the field sizes, and reordering fields can change it.
#include <stdio.h>
#include <stddef.h>
struct a { char c; int i; };
struct b { char c1; int i; char c2; };
struct c { int i; char c1; char c2; };
int main(void) {
printf("%zu %zu %zu\n", sizeof(struct a), sizeof(struct b), sizeof(struct c));
printf("%zu\n", offsetof(struct a, i));
return 0;
}On a typical platform with 4-byte int, this prints 8 12 8 and then 4. The exact numbers depend on the platform's alignment rules, and GATE questions normally state the assumptions you need.
Self-referential structs
A struct cannot contain itself, because its size would be infinite. It can contain a pointer to its own type, because a pointer has a fixed size:
struct node {
int data;
struct node *next;
};Each node holds a value and the address of the next node. The last node's next is NULL. The list itself is represented by a single struct node * called the head.
Nodes live on the heap, so they are allocated one at a time with malloc. They are usually not contiguous in memory. That is why a list has no indexing: reaching the k-th node means following next k times.
Core operations
The program below implements insertion at the head, printing, in-place reversal, deletion by value, and cleanup.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *push(struct node *head, int v) {
struct node *n = malloc(sizeof *n);
if (n == NULL) {
return head;
}
n->data = v;
n->next = head;
return n;
}
void print_list(const struct node *h) {
for (; h != NULL; h = h->next) {
printf("%d ", h->data);
}
printf("\n");
}
struct node *reverse(struct node *head) {
struct node *prev = NULL;
while (head != NULL) {
struct node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
void remove_first(struct node **head, int v) {
struct node **pp = head;
while (*pp != NULL && (*pp)->data != v) {
pp = &(*pp)->next;
}
if (*pp != NULL) {
struct node *t = *pp;
*pp = t->next;
free(t);
}
}
void free_list(struct node *h) {
while (h != NULL) {
struct node *t = h->next;
free(h);
h = t;
}
}
int main(void) {
struct node *head = NULL;
for (int i = 1; i <= 3; i++) {
head = push(head, i);
}
print_list(head);
head = reverse(head);
print_list(head);
remove_first(&head, 2);
print_list(head);
free_list(head);
return 0;
}The output is:
3 2 1
1 2 3
1 3 Why `push` returns the head
push receives a copy of the caller's head. Assigning to that copy inside the function would not change the caller's variable. There are two fixes: return the new head and have the caller assign it, or pass struct node ** and write through it. remove_first uses the second fix because the head may itself be the node being removed.
Why `remove_first` uses a pointer to pointer
The variable pp holds the address of the pointer that points to the current node. That pointer is either head or some node's next field. Unlinking is then the single assignment *pp = t->next, with no special case for the first node and no prev pointer.
Why `free_list` saves `next` first
After free(h), reading h->next is a use after free, which is undefined behavior. The code copies next into t before freeing.
Complexity
| Operation | Cost |
|---|---|
| Insert at head | O(1) |
| Insert at tail, with only a head pointer | O(n) |
| Insert after a node you already hold | O(1) |
| Search by value | O(n) |
| Access the k-th element | O(k) |
| Delete a node, given the pointer to its predecessor | O(1) |
| Reverse | O(n) time, O(1) extra space |
Keeping a separate tail pointer makes tail insertion O(1). It does not help with deleting the tail, because you still need the predecessor and a singly linked list has no backward link.
Common errors
- Wrong allocation size.
malloc(sizeof(struct node *))allocates room for a pointer, not a node. Prefermalloc(sizeof *n), which stays correct if the type changes. - Unchecked
malloc. It returnsNULLon failure, and dereferencing that is undefined behavior. - Uninitialized
next. If the last node'snextis notNULL, traversal runs off the end. - Losing the head. Moving
headforward during a traversal without keeping a copy leaks every node you passed. - Dereferencing
NULL. A loop condition such asp->next != NULLfails on an empty list unless you testpfirst. - Double free and use after free. Free each node exactly once, and do not read it afterwards.
Exercises
Exercise
A list holds 1 -> 2 -> 3 -> NULL and head points to the node with 1. What does the list look like after running head->next = head->next->next;, and what problem does this code have?
Show answer
The list becomes 1 -> 3 -> NULL. The node holding 2 is no longer reachable and was never freed, so it is a memory leak. The correct version saves the pointer to that node, relinks, then frees it.
Exercise
Why does the following function fail to add a node to the caller's list, and how can it be fixed? void add_front(struct node head, int v) { struct node n = malloc(sizeof *n); n->data = v; n->next = head; head = n; }
Show answer
head is a copy of the caller's pointer, so the assignment head = n changes only the local copy, and the new node leaks. Fix it by returning the new head (struct node *add_front(struct node *head, int v)) or by taking struct node **head and assigning *head = n.
Exercise
On a platform with 4-byte int, 1-byte char, and 4-byte alignment for int, what is sizeof(struct { char a; int b; char c; })? What is it if the fields are reordered as int, char, char?
Show answer
12 for the original order: a at offset 0, 3 bytes of padding, b at offset 4, c at offset 8, then 3 bytes of tail padding. With the order int, char, char it is 8, because the two chars sit together at offsets 4 and 5 and only 2 bytes of tail padding are needed.