🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Linked List Join Rotate
Concatenate two linked lists and rotate the first node to the end without losing nodes.
Linked List Join and Rotate in C
Two exercises in this free C programming course chapter work on the structure of a list itself rather than on the data inside it: concatenate one linked list at the end of another, and remove the first node of a list and insert it at the end. Both reduce to the same skill, which is rewiring next pointers without losing a node or creating a loop. That skill is the foundation of queues, buffer pools and task lists in embedded C programming.
This lecture explains the pointer moves with diagrams, then gives you a complete program that builds two lists, joins them, rotates the result, and tests the awkward cases: an empty list and a single-node list. You will see the real output and learn the ownership rule that prevents the most common crash with joined lists.
What You Will Learn
- How a singly linked list node refers to the next node through a self-referential structure
- How to append a node when the list may be empty
- How to concatenate two lists by changing one pointer
- How to move the first node to the end in a single pass
- How to handle empty and one-node lists without special-case bugs
- Who owns the nodes after a join, and how to free them exactly once
Prerequisites
You should know how to declare struct node { int value; struct node *next; }, allocate with malloc(), and walk a list with a loop. This lecture belongs to the free embedded C course structure chapter, right after self-referential structures and list traversal.
The Node and the Head Pointer
A list is nothing more than a head pointer plus nodes that point to each other. An empty list is the head pointer holding NULL. Every operation that might change which node is first must therefore return the new head, or receive the address of the head. This program returns the head, which keeps the calls easy to read: a = concat(a, b);.
Concatenating Two Lists
To join list b after list a, find the last node of a, the one whose next is NULL, and set that pointer to the head of b. No node is copied and no memory is allocated; one pointer assignment does the whole job. The special case is an empty a: there is no last node, so the answer is simply b.
Ownership rule:
After the join, the nodes of b belong to the joined list. If you later free list a and then free list b, the second free hits memory that is already gone, which is a double free. Free the combined list once, and treat b as an alias you must not use for freeing.
Moving the First Node to the End
This operation is a rotation by one position. It has four steps, and the order matters because you must not lose the rest of the list while you detach the first node.
- If the list is empty or has only one node, return it unchanged; rotating cannot change anything.
- Remember the first node in a local pointer and advance the head to the second node.
- Set the remembered node’s
nexttoNULLso it becomes a standalone node. - Walk to the new last node and attach the remembered node there. Return the new head.
| List before | After one rotation | Why |
|---|---|---|
| 1 2 3 4 5 | 2 3 4 5 1 | Normal case |
| 7 | 7 | Single node: nothing to move |
| (empty) | (empty) | No first node exists |
| 8 9 | 9 8 | Two nodes: swap in effect |
The Complete Program
The helper append() adds a node at the tail and returns the head. concat() and rotate_first_to_last() implement the two exercise operations. print_list() prints a label and the values, showing (empty) for an empty list, and free_list() releases the nodes by saving each next pointer before freeing the node that holds it.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
static struct node *append(struct node *head, int value)
{
struct node *n = malloc(sizeof *n);
if (!n) {
return head;
}
n->value = value;
n->next = NULL;
if (!head) {
return n;
}
struct node *t = head;
while (t->next) {
t = t->next;
}
t->next = n;
return head;
}
/* Hook list b after list a. Afterwards b's nodes belong to the joined list. */
static struct node *concat(struct node *a, struct node *b)
{
if (!a) {
return b;
}
struct node *t = a;
while (t->next) {
t = t->next;
}
t->next = b;
return a;
}
/* Detach the first node and re-attach it at the tail. */
static struct node *rotate_first_to_last(struct node *head)
{
if (!head || !head->next) {
return head; /* empty or single node: nothing to do */
}
struct node *first = head;
head = head->next;
first->next = NULL;
struct node *t = head;
while (t->next) {
t = t->next;
}
t->next = first;
return head;
}
static void print_list(const char *label, const struct node *h)
{
printf("%-14s:", label);
if (!h) {
printf(" (empty)");
}
for (; h; h = h->next) {
printf(" %d", h->value);
}
putchar('\n');
}
static void free_list(struct node *h)
{
while (h) {
struct node *next = h->next;
free(h);
h = next;
}
}
int main(void)
{
struct node *a = NULL, *b = NULL, *empty = NULL;
for (int i = 1; i <= 3; i++) {
a = append(a, i);
}
for (int i = 4; i <= 5; i++) {
b = append(b, i);
}
print_list("list a", a);
print_list("list b", b);
a = concat(a, b); /* b is now part of a */
print_list("a + b", a);
a = rotate_first_to_last(a);
print_list("rotate once", a);
a = rotate_first_to_last(a);
print_list("rotate twice", a);
empty = concat(empty, NULL);
print_list("empty + empty", empty);
empty = rotate_first_to_last(empty);
print_list("rotate empty", empty);
free_list(a); /* frees b's nodes too; never free b again */
return 0;
}Build and Run
gcc -std=c11 -Wall -Wextra -o ep_listjoin ep_listjoin.c
./ep_listjoinlist a : 1 2 3
list b : 4 5
a + b : 1 2 3 4 5
rotate once : 2 3 4 5 1
rotate twice : 3 4 5 1 2
empty + empty : (empty)
rotate empty : (empty)Read the output as a story. The two lists print separately, the join produces one list, two rotations move 1 and then 2 to the back, and the last two lines confirm that an empty list stays empty through both operations.
Walking Through the Pointers
Consider the rotate step on 1 2 3 4 5. Before the call, head points at node 1. The function stores that address in first and moves head to node 2. At this moment node 1 is still linked to node 2, so the code sets first->next = NULL to cut it free. A loop then advances t until t->next is NULL, which is node 5, and the final assignment t->next = first hangs node 1 after node 5. The function returns the new head, node 2.
If you swap the order of the second and third steps, you would clear first->next before advancing the head, and the rest of the list would become unreachable. That is a memory leak and a very confusing output. When pointer code goes wrong, draw boxes and arrows on paper, one picture per statement.
The cost is also worth knowing. Both concat() and rotate_first_to_last() walk the whole list to find the tail, so each takes time proportional to the length. Keeping an extra tail pointer in a small wrapper structure would make appending and rotating constant time, a common trick in queues.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Dereferencing a->next when a is NULL | Segmentation fault on an empty list | Test for NULL first and return the other list |
Not setting the detached node’s next to NULL | List loops forever or prints duplicates | Clear it before attaching |
| Freeing both lists after a join | Double free abort | Free only the joined head |
Ignoring the return value of concat | Head pointer stays stale when a was empty | Always assign the result back |
| Losing the head while walking | Cannot free or print later | Walk with a separate pointer t |
Unchecked malloc | Crash on low memory | Test for NULL as append() does |
Tip:
Compile with -fsanitize=address,undefined while learning. The sanitizer reports a double free or a leak with a stack trace the moment it happens.
Best Practices
- Return the head from every function that can change it, and assign it back at the call site.
- Handle the empty and single-node lists first; the general case then follows naturally.
- Decide on and document ownership whenever two lists are merged.
- Use a
constpointer in functions that only read, such asprint_list(). - On a microcontroller, prefer nodes taken from a static pool over
malloc()to avoid fragmentation.
Performance and security notes:
Pointer-chasing lists are slower than arrays because nodes may be scattered in memory, so use them when you need cheap insertion and removal, not for fast indexing. A corrupted next pointer can turn a list walk into an infinite loop, so in safety-critical code add a maximum-length guard to every traversal.
Summary and Key Takeaways
- Concatenation is one pointer assignment after finding the tail.
- Rotation detaches the head, walks to the tail and re-attaches it.
- Empty and single-node lists must be handled explicitly.
- After joining, the combined list owns every node; free it once.
- Drawing the pointers is the fastest way to debug list code.
Conclusion
You can now splice and rotate lists with confidence, and you know exactly where such code fails. The next lecture in this free C programming course traverses a list once to count occurrences of a value and to find the smallest value, the largest value, the total and the average.
Frequently Asked Questions
Does concatenation copy any nodes?
No. It only changes one next pointer, so it runs without allocating memory.
Why does rotate return a pointer?
The first node changes, so the caller needs the new head.
What happens if I concatenate a list with itself?
The last node would point back at the head, creating a cycle and an endless traversal. Avoid it.
Can I rotate by more than one position?
Yes. Call the function repeatedly, or find the k-th node and re-link once for better efficiency.
Why not keep a tail pointer?
It is a good optimisation, but it requires a wrapper structure; this lecture keeps the node type minimal for clarity.
How do I detect a loop in a list?
Use two pointers where one moves two steps for every one step of the other; they meet if a loop exists.
Keep Learning C for Free
Keep going through the structure chapter with free, original embedded C programming lectures.
<
1 Comment