🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Linked List Insert Delete
Free C tutorial: insert a node after a chosen position and delete a node from the front, middle or end of a singly linked list.
Adding nodes at the ends is easy. Real programs also need to insert in the middle and remove items that are no longer needed, and this is where most students make their first pointer mistakes. In this lecture of our free C programming course we build insert_after() and remove_value() for a linked list in C, and we study every edge case: empty list, first node, last node and value not found. These patterns are core embedded C programming skills, because removing a finished task or an expired timer from a list is something real firmware does all the time.
If you are looking for a free embedded C course that explains the reasons behind each pointer assignment, you are in the right place.
What You Will Learn
- How to insert a node after the n-th node of a linked list
- Why the order of the two pointer assignments in an insert is critical
- The three cases of deleting a node: first, middle and last
- How a trailing
prevpointer makes deletion simple - How to avoid leaks and dangling pointers when you call
free() - How to test all edge cases with a menu program
Prerequisites
- The previous lecture: node structure,
push_front()andpush_back() - Pointer to pointer and call by reference
- Loops with two conditions such as
forandwhile
Insert After a Given Position
The user says: put the value 15 after the second node. We number nodes from one. To do the insert we need the address of that second node, which we find by walking the list. Once we hold it, the insert is just two pointer changes.
Insert 15 after position 2
cur->next = new, the only copy of the address of node 20 is gone, and everything after the insertion point is lost.
int insert_after(struct node *head, int pos, int value)
{
struct node *cur = head;
struct node *n;
int i;
if (pos < 1)
return -1;
for (i = 1; i < pos && cur != NULL; i++)
cur = cur->next;
if (cur == NULL)
return -1;
n = make_node(value);
if (n == NULL)
return -2;
n->next = cur->next;
cur->next = n;
return 0;
}
How the position loop works
We start with cur on node 1 and counter i equal to 1. Each loop pass moves cur one node forward and increases i. When i reaches pos, cur points to the node we want. The extra test cur != NULL stops the loop if the list is shorter than the requested position. After the loop we test cur == NULL once more, because the loop might have ended for that reason. Only then is it safe to allocate and link.
| Input | Result | Return value |
|---|---|---|
| Empty list, any position | Nothing inserted | -1 |
| Position 0 or negative | Nothing inserted | -1 |
| Position larger than length | Nothing inserted | -1 |
| Position equal to length | Behaves like add at back | 0 |
| Allocation failure | Nothing inserted | -2 |
Notice that this function takes struct node *head, not the double pointer. It never changes the head, because the new node always goes after an existing node. Using the simplest signature that works is good design: it tells the reader that the head is safe.
Deleting a Node: Three Cases
To delete a value we must first find it, and then unlink it. Unlinking means making the node before it skip over it. That is why deletion needs two pointers moving together: cur on the node to remove and prev on the node just behind it.
| Case | Where the value is | What changes |
|---|---|---|
| 1 | First node | head moves to the second node |
| 2 | Middle node | prev->next skips over cur |
| 3 | Last node | prev->next becomes NULL |
| 4 | Not present | Nothing; report failure |
Deleting a middle node (value 15)
Deleting the first node (value 5)
One function, all cases
The trick is that when the value sits in the first node, prev is still NULL. So a single test, prev == NULL, separates case 1 from cases 2 and 3. Middle and last deletions are literally the same line of code, because the last node’s next is already NULL.
int remove_value(struct node **head, int value)
{
struct node *prev = NULL;
struct node *cur = *head;
while (cur != NULL && cur->value != value) {
prev = cur;
cur = cur->next;
}
if (cur == NULL)
return -1;
if (prev == NULL)
*head = cur->next;
else
prev->next = cur->next;
free(cur);
return 0;
}
Here is the loop condition in plain words: keep walking while there is a node and it is not the one we want. When the loop stops, either cur is NULL (value not found) or cur holds the match. The order in the condition is important: cur != NULL must come first, so C never reads cur->value through a null pointer. This short-circuit behaviour of && protects you.
Duplicates
This function removes only the first node holding the value. If the list holds 10, 20, 10 and you delete 10, the result is 20, 10. To remove all matches, call it in a loop until it returns -1.
Free the Node, Then Forget It
After free(cur), the variable cur still holds the old address, but that memory no longer belongs to you. Using it is a dangling pointer bug. In our function we return right after freeing, so there is no chance of misuse. Never read cur->next after free(cur); copy what you need before you free.
Wiring Both Functions to the Menu
case 3:
if (ask("Value: ", &value) && ask("After position: ", &pos)) {
if (insert_after(head, pos, value) != 0)
printf("Cannot insert: list has fewer than %d nodes\n", pos);
}
break;
case 4:
if (head == NULL) {
printf("List is empty\n");
break;
}
if (ask("Value to delete: ", &value) &&
remove_value(&head, value) != 0)
printf("%d not found\n", value);
break;
The empty-list check in case 4 is polite to the user: we avoid asking for a value when there is nothing to delete. The function itself is already safe on an empty list, so this is a convenience, not a protection.
Test Plan and Expected Output
Always test deletion with these inputs. Starting from the list 5, 10, 20, 30:
| Action | Expected list |
|---|---|
| Insert 15 after position 2 | 5 10 15 20 30 |
| Delete 20 (middle) | 5 10 15 30 |
| Delete 5 (first) | 10 15 30 |
| Delete 30 (last) | 10 15 |
| Delete 99 (absent) | 10 15, message “99 not found” |
| Insert after position 9 | No change, error message |
Running our program with scripted input produced this tail of output for the middle deletion and the failed search:
Choice: List: 5 10 15 30
Choice: Value to delete: 99 not found
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Linking cur->next = n first | Tail of list lost | Set n->next first |
Forgetting free() after unlink | Memory leak | Free the removed node |
| Freeing before unlinking | Crash or garbage | Unlink, then free |
Not updating head when the first node is deleted | Head points to freed memory | Use prev == NULL test |
Testing cur->value before cur != NULL | Segmentation fault | Put the null test first |
| Off-by-one in the position loop | Insert lands one place wrong | Trace with a 3-node list on paper |
Best Practices and Performance
- Draw the nodes and arrows on paper before coding any pointer change.
- Handle the first node through the same code path where possible, as
remove_value()does. - Both functions walk the list, so each costs O(n). Deleting a node you already hold a pointer to is cheaper if you keep a doubly linked list.
- Run with
gcc -fsanitize=address,undefinedto catch leaks and use-after-free during practice. - In firmware that must never fragment the heap, return nodes to a static pool rather than calling
free().
Key Takeaways
- Insert: link the new node to the rest first, then link the earlier node to it.
- Delete: keep a
prevpointer; the first node is the case whereprevisNULL. - Always test: empty list, one node, first, middle, last, absent.
- Free exactly once and never touch the node afterwards.
Conclusion
You can now grow and shrink a linked list at any position without losing nodes or leaking memory. In the next lecture we complete the menu program with display and search, add cleanup, and run the finished program end to end. If you want a structured free C tutorial path toward C programming for embedded systems, keep going through this series.
Frequently Asked Questions
Why do we need a prev pointer to delete a node?
A singly linked node knows only its successor. To remove a node, the previous node must be redirected, so we must remember it while walking.
What happens if I delete the only node in the list?
prev is NULL, so head becomes cur->next, which is NULL. The list is empty again.
Can insert_after add a node before the first node?
No. Use push_front for that. Position 1 means after the first node.
Is it safe to call free on a node I just unlinked?
Yes, and you must. After the unlink nothing in the list points to it, so freeing it is correct.
How do I delete by position instead of by value?
Walk with a counter instead of comparing values, keeping the same prev and cur pair, then unlink the same way.
Why return error codes instead of printing inside the functions?
Library-style functions should report and let the caller decide how to react. That keeps them reusable on devices that have no console.
Keep Learning Embedded C for Free
Next: display, search and the complete menu program.

2 Comments