🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Linked List Insert After Node
Insert a node in the middle or at the end of a singly linked list in C, using the two-statement relink and a pointer-to-pointer append that works on empty lists too.
This lecture of our free C programming course covers the other two places a node can go: somewhere in the middle and at the very end. You already know head insertion from the previous lecture. Middle and end insertion look harder, but they reduce to one idea: find the node that will sit before the new one, then rewire exactly two pointers. Whether you are working through this free C tutorial for a university exam or learning embedded C programming for firmware interviews, this is the pattern behind sorted lists, ordered schedulers and append-only logs.
What You Will Learn
- How to insert a node after any node you hold a pointer to
- Why inserting at the end is the same operation as inserting in the middle
- How to find the “previous” node by key or by position
- A compact pointer-to-pointer append that needs no special case for an empty list
- How to build and test the full program and read its output
Prerequisites
Finish the previous lecture on head insertion first. You should know the node_t structure, make_node() and how push_front() uses a pointer to the head. Everything in this free embedded C course chapter reuses those helpers.
The Key Idea: Find the Previous Node
A singly linked list can only move forward. A node has no idea who points at it. So to insert “between A and C”, you must stand on A, because A is the node whose next has to change. Call it prev. The new node B must do two things: point forward at what A used to point to, and then be pointed to by A.
Before: prev stands on 20, we want 30 between 20 and 40
Statement 1: fresh->next = prev->next
Statement 2: prev->next = fresh
Just like head insertion, order matters. If you did prev->next = fresh first, the only pointer to 40 would be overwritten and the tail of the list would be lost. Link the new node forward first, then link the old node to it.
Linked List Insert at the End Is Not Special
Many beginners write a separate branch for the last node. You do not need one. If prev is the last node, then prev->next is NULL. Statement 1 copies that NULL into the new node, which is exactly what the last node of a list should hold. Statement 2 then attaches it. Same two lines, no extra code.
| Case | Value of prev | prev->next before | New node ends up |
|---|---|---|---|
| Middle | Any inner node | The next node | Between two nodes |
| End | Last node | NULL | Last node, with next = NULL |
| Beginning | (none exists) | – | Needs head insertion instead |
Finding the Node to Insert After
There are two common ways to choose prev. By key: walk until a node’s value equals what you were told, and return that node or NULL. By position: walk index - 1 steps from the head. Both are O(n), so the whole insertion costs O(n) even though the relink itself is O(1). That is the real price of lists compared with arrays in C programming for embedded systems: easy to insert, slow to find.
Appending with a pointer to pointer
To append without keeping a tail pointer, walk using the address of each next field rather than the node itself. Start with pp = head, the address of the head variable. While *pp is not NULL, move pp to the address of that node’s next. When the loop ends, pp holds the address of the empty slot where the new node belongs, and one assignment *pp = fresh fills it. Because the head variable is the first slot, an empty list needs no special case at all.
pp walks along the slots, stopping at the first empty one
Complete Insert After Node Program
The program below defines find(), insert_after(), append() and insert_at(), then exercises them including two deliberate failures to prove the error paths work.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
} node_t;
static node_t *make_node(int value)
{
node_t *n = malloc(sizeof *n);
if (n == NULL)
return NULL;
n->value = value;
n->next = NULL;
return n;
}
static void print_list(const node_t *head)
{
for (const node_t *p = head; p != NULL; p = p->next)
printf("%d -> ", p->value);
printf("NULL\n");
}
static void free_list(node_t *head)
{
while (head != NULL) {
node_t *next = head->next;
free(head);
head = next;
}
}
static int push_front(node_t **head, int value)
{
node_t *n = make_node(value);
if (n == NULL)
return -1;
n->next = *head;
*head = n;
return 0;
}
static node_t *find(node_t *head, int key)
{
for (node_t *p = head; p != NULL; p = p->next)
if (p->value == key)
return p;
return NULL;
}
/* insert a new node right after 'prev' (middle or end) */
static int insert_after(node_t *prev, int value)
{
if (prev == NULL)
return -1;
node_t *n = make_node(value);
if (n == NULL)
return -1;
n->next = prev->next; /* statement 1: new node points forward */
prev->next = n; /* statement 2: previous node points to new node */
return 0;
}
/* append at the end; the pointer-to-pointer walk also handles an empty list */
static int append(node_t **head, int value)
{
node_t *n = make_node(value);
if (n == NULL)
return -1;
node_t **pp = head;
while (*pp != NULL)
pp = &(*pp)->next;
*pp = n;
return 0;
}
/* insert so that the new node ends up at position 'index' (0-based) */
static int insert_at(node_t **head, size_t index, int value)
{
if (index == 0)
return push_front(head, value);
node_t *prev = *head;
for (size_t i = 1; i < index && prev != NULL; i++)
prev = prev->next;
return insert_after(prev, value); /* NULL prev => index out of range */
}
int main(void)
{
node_t *head = NULL;
append(&head, 10);
append(&head, 20);
append(&head, 40);
print_list(head);
insert_after(find(head, 20), 30);
print_list(head);
append(&head, 50);
print_list(head);
insert_at(&head, 0, 5);
print_list(head);
insert_at(&head, 3, 15);
print_list(head);
if (insert_at(&head, 99, 1) != 0)
printf("index 99 rejected\n");
if (insert_after(find(head, 777), 1) != 0)
printf("key 777 not found\n");
free_list(head);
return 0;
}
Build and run
gcc -std=c11 -Wall -Wextra -g -fsanitize=address,undefined -o ll_insert ll32.c
./ll_insert
Expected output:
10 -> 20 -> 40 -> NULL
10 -> 20 -> 30 -> 40 -> NULL
10 -> 20 -> 30 -> 40 -> 50 -> NULL
5 -> 10 -> 20 -> 30 -> 40 -> 50 -> NULL
5 -> 10 -> 20 -> 15 -> 30 -> 40 -> 50 -> NULL
index 99 rejected
key 777 not found
Reading the output line by line
- Lines 1 to 3 build 10, 20, 40, add 30 after 20, then append 50.
- Line 4 pushes 5 at index 0, which delegates to head insertion.
- Line 5 inserts 15 at index 3, so it lands after 20 and before 30.
- The last two lines show that an out-of-range index or a missing key is refused rather than corrupting memory.
Why insert_at(index 0) calls push_front
Position 0 has no previous node, so the “after a node” rule cannot apply. Delegating to head insertion keeps each function focused and avoids a duplicate code path.
Common Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Passing a NULL prev without checking | Crash on prev->next | Return an error when prev is NULL |
| Doing prev->next = fresh first | Rest of the list lost | Set fresh->next first |
| Walking too far (loop uses <= instead of <) | Insert lands one place late | Walk index – 1 steps |
| Writing a special case for the empty list in append | More code, more bugs | Use the pointer-to-pointer walk |
| Not freeing the node when later steps fail | Leak | Allocate last, or free before returning an error |
Best Practices and Performance
- If you append often, store a tail pointer next to the head. Appending becomes O(1), but you must update the tail when the list was empty and when you delete the last node.
- Validate indices that come from user input or a serial command before you walk.
- Keep traversal read-only (use
const node_t *) and keep mutation in small named functions. - On a microcontroller, remember each node costs the payload plus a pointer, and the allocator may add its own header on top.
Summary and Key Takeaways
- Middle and end insertion share one pattern: fresh->next = prev->next, then prev->next = fresh.
- You need the previous node; finding it is the O(n) part.
- A pointer-to-pointer walk makes append work for empty and non-empty lists alike.
- Check every pointer that could be NULL before dereferencing it.
That finishes insertion in this free C programming course chapter. Next we remove nodes safely and give their memory back.
Frequently Asked Questions
Can I insert before a given node in a singly linked list?
Not directly, because you cannot step backwards. Either find the previous node, or use the pointer-to-pointer walk which stops on the slot that points at the target.
Is insertion in a linked list always O(1)?
The relink is O(1), but finding the place is usually O(n). Only head insertion, or insertion after a node you already hold, is truly O(1) overall.
Do I need a tail pointer for append?
Not for correctness. It is an optimisation that turns repeated appends from O(n) each into O(1) each.
What if the list is empty when I call append?
With the pointer-to-pointer walk the loop body never runs and the new node is stored directly in the head variable. No special case is needed.
Why does embedded C programming avoid many small mallocs?
Repeated allocation can fragment a small heap and has non-deterministic timing. Many firmware projects use a static pool instead.
Is this free C tutorial enough for interviews?
It covers the core insertion cases interviewers ask about. The final lecture of this chapter adds a quiz and interview questions.
Free Embedded C Course for Students
Build the habit of drawing the pointers before writing the code. It is the fastest way to stop making linked list bugs.

2 Comments