Union and intersection of two linked lists in C: a step-by-step visualizer
The union of two linked lists holds every value that is in either list, once. The intersection holds the values that are in both. The usual C method walks one list and searches the other for each node, which takes up to n × m comparisons: 10,00,00,000 (10 crore) for two 10,000-node lists. Keep both lists sorted and one merge pass needs at most n + m − 1, here 19,999.
Type two lists and watch each method run node by node, with the comparisons, malloc and free calls counted. Each method comes with a complete C program, and a second tab checks the output your own program prints. This is Project 1 of Skill-Lync's Embedded Programming Essentials course, "user interfaces for working with Sets" using two linked lists. The third tab is the linked queue project.
C11 (N1570) · every C program here compiled with -Wall -Wextra -Werror and ASan + UBSan, run on 246 cases · checked against a separate solution (52,886 checks at build) · Updated 24 Nov 2026
Up to 200 values per list; the animation draws lists of up to 16 nodes. One comparison is one test of two values: in the merge, a three-way compare counts once.
The default is real output: a public report's program (functions copied unchanged) run on A = 1 2 2 3 and B = 2 3 4. Words, labels and arrows are ignored; the numbers are read in order.
The default runs out of nodes and enqueues again: the step where the rear slip shows. Tick the box to see it.
done: 7 nodes in the result
Result in linked order6 → 7 → 1 → 2 → 3 → 4 → 5 → NULL
As a set (sorted){1, 2, 3, 4, 5, 6, 7}
Same values as the set union, in another order: B's new values come first because the method inserts at the head. A set has no order, so this is right.
- Union: no value missing
- Union: 2 appears 2 times: not a set
- Intersection: no value missing
- Intersection: 2 appears 2 times: not a set
- Union order: the same order the head-insert report method prints (B's new values first, then A). Fine for a set.
Correct union {1, 2, 3, 4}, intersection {2, 3}.
Tick what your own code does
0 of 5 ticked. The five slips are explained under "Common slips" below.
show the queue
Dequeued 10 Dequeued 20 Front 30 Queue: 30 -> NULL
The complete C program: report-method.c
/* Union, intersection and difference of two linked lists in C, done the way
most student reports do it: every insert puts the new node at the head, the
union copies list A without a membership check, and each element of B is
searched for in the result built so far (O(n*m) comparisons).
Input: n, then n integers for A; m, then m integers for B.
Prompts go to stderr and results to stdout, so the output can be compared. */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
/* Insert at the head: O(1), but the list ends up in reverse input order. */
static int push(struct Node **head, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return 0;
node->data = value;
node->next = *head;
*head = node;
return 1;
}
/* 1 if value is in the list, else 0. Keep the final return 0: a function
that reaches its closing brace without returning gives the caller an
undefined value (C11 6.9.1p12). */
static int is_present(const struct Node *head, int value)
{
for (const struct Node *t = head; t != NULL; t = t->next)
if (t->data == value)
return 1;
return 0;
}
/* Union, report style. List A is copied with no check, so a value that
appears twice in A appears twice in the result: the result is not a set.
B's elements are checked against the result, so B's duplicates are dropped. */
static int get_union(const struct Node *a, const struct Node *b, struct Node **out)
{
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (!push(out, t1->data))
return 0;
for (const struct Node *t2 = b; t2 != NULL; t2 = t2->next)
if (!is_present(*out, t2->data) && !push(out, t2->data))
return 0;
return 1;
}
/* Intersection, report style: walk A and search B. A value that appears
twice in A and once in B appears twice in the result. */
static int get_intersection(const struct Node *a, const struct Node *b, struct Node **out)
{
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (is_present(b, t1->data) && !push(out, t1->data))
return 0;
return 1;
}
/* Difference A - B in the same style: elements of A not found in B. */
static int get_difference(const struct Node *a, const struct Node *b, struct Node **out)
{
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (!is_present(b, t1->data) && !push(out, t1->data))
return 0;
return 1;
}
static void print_list(const char *label, const struct Node *head)
{
printf("%s: ", label);
for (const struct Node *t = head; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
static void free_list(struct Node *head)
{
while (head != NULL) {
struct Node *next = head->next;
free(head);
head = next;
}
}
/* Reads a count, then that many integers, pushing each at the head. */
static int read_list(const char *name, struct Node **head)
{
int n, value;
fprintf(stderr, "Number of elements in %s: ", name);
if (scanf("%d", &n) != 1 || n < 0)
return 0;
fprintf(stderr, "Enter %d integers: ", n);
for (int i = 0; i < n; i++)
if (scanf("%d", &value) != 1 || !push(head, value))
return 0;
return 1;
}
int main(void)
{
struct Node *a = NULL, *b = NULL, *u = NULL, *in = NULL, *d = NULL;
int ok = read_list("A", &a) && read_list("B", &b)
&& get_union(a, b, &u) && get_intersection(a, b, &in)
&& get_difference(a, b, &d);
if (ok) {
print_list("A", a);
print_list("B", b);
print_list("Union", u);
print_list("Intersection", in);
print_list("A - B", d);
} else {
fprintf(stderr, "Error: bad input or out of memory\n");
}
free_list(a);
free_list(b);
free_list(u);
free_list(in);
free_list(d);
return ok ? 0 : 1;
}
/* Union, intersection and difference of two linked lists in C, treating each
list as a set: insert refuses a value that is already there, so neither
list holds a duplicate, and the results keep the input order.
Union and intersection still search one list for each element of the
other, so they cost up to n*m comparisons.
Input: n, then n integers for A; m, then m integers for B.
Prompts go to stderr and results to stdout, so the output can be compared. */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
/* 1 if value is in the list, else 0. */
static int contains(const struct Node *head, int value)
{
for (const struct Node *t = head; t != NULL; t = t->next)
if (t->data == value)
return 1;
return 0;
}
/* Adds value at the tail unless it is already in the list.
Returns 1 if added, 0 if it was a duplicate, -1 if malloc failed. */
static int insert(struct Node **head, int value)
{
struct Node **link = head;
while (*link != NULL) {
if ((*link)->data == value)
return 0;
link = &(*link)->next;
}
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return -1;
node->data = value;
node->next = NULL;
*link = node;
return 1;
}
/* Appends at *tail, the address of the last next pointer, in O(1). */
static int append(struct Node ***tail, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return 0;
node->data = value;
node->next = NULL;
**tail = node;
*tail = &node->next;
return 1;
}
/* A is a set already, so it is copied whole; then each element of B that is
not in A is added. */
static int set_union(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (!append(&tail, t1->data))
return 0;
for (const struct Node *t2 = b; t2 != NULL; t2 = t2->next)
if (!contains(a, t2->data) && !append(&tail, t2->data))
return 0;
return 1;
}
static int set_intersection(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (contains(b, t1->data) && !append(&tail, t1->data))
return 0;
return 1;
}
static int set_difference(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
for (const struct Node *t1 = a; t1 != NULL; t1 = t1->next)
if (!contains(b, t1->data) && !append(&tail, t1->data))
return 0;
return 1;
}
static void print_list(const char *label, const struct Node *head)
{
printf("%s: ", label);
for (const struct Node *t = head; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
static void free_list(struct Node *head)
{
while (head != NULL) {
struct Node *next = head->next;
free(head);
head = next;
}
}
/* Reads a count, then that many integers; duplicates are skipped. */
static int read_list(const char *name, struct Node **head)
{
int n, value;
fprintf(stderr, "Number of elements in %s: ", name);
if (scanf("%d", &n) != 1 || n < 0)
return 0;
fprintf(stderr, "Enter %d integers: ", n);
for (int i = 0; i < n; i++)
if (scanf("%d", &value) != 1 || insert(head, value) < 0)
return 0;
return 1;
}
int main(void)
{
struct Node *a = NULL, *b = NULL, *u = NULL, *in = NULL, *d = NULL;
int ok = read_list("A", &a) && read_list("B", &b)
&& set_union(a, b, &u) && set_intersection(a, b, &in)
&& set_difference(a, b, &d);
if (ok) {
print_list("A", a);
print_list("B", b);
print_list("Union", u);
print_list("Intersection", in);
print_list("A - B", d);
} else {
fprintf(stderr, "Error: bad input or out of memory\n");
}
free_list(a);
free_list(b);
free_list(u);
free_list(in);
free_list(d);
return ok ? 0 : 1;
}
/* Union, intersection and difference of two linked lists in C by sorted
merge: insert keeps each list sorted and free of duplicates, then one pass
down both lists at once gives each result in O(n + m) comparisons.
Input: n, then n integers for A; m, then m integers for B.
Prompts go to stderr and results to stdout, so the output can be compared. */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
/* Inserts value in sorted position unless it is already there.
Returns 1 if added, 0 if it was a duplicate, -1 if malloc failed. */
static int insert_sorted(struct Node **head, int value)
{
struct Node **link = head;
while (*link != NULL && (*link)->data < value)
link = &(*link)->next;
if (*link != NULL && (*link)->data == value)
return 0;
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return -1;
node->data = value;
node->next = *link;
*link = node;
return 1;
}
/* Appends at *tail, the address of the last next pointer, in O(1). */
static int append(struct Node ***tail, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return 0;
node->data = value;
node->next = NULL;
**tail = node;
*tail = &node->next;
return 1;
}
/* Copies the rest of a list to the tail of the result. */
static int append_rest(struct Node ***tail, const struct Node *t)
{
for (; t != NULL; t = t->next)
if (!append(tail, t->data))
return 0;
return 1;
}
/* Both lists are sorted: take the smaller head each step; on a tie take it
once and advance both. */
static int merge_union(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
while (a != NULL && b != NULL) {
int v;
if (a->data < b->data) {
v = a->data;
a = a->next;
} else if (b->data < a->data) {
v = b->data;
b = b->next;
} else {
v = a->data;
a = a->next;
b = b->next;
}
if (!append(&tail, v))
return 0;
}
return append_rest(&tail, a) && append_rest(&tail, b);
}
static int merge_intersection(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
while (a != NULL && b != NULL) {
if (a->data < b->data) {
a = a->next;
} else if (b->data < a->data) {
b = b->next;
} else {
if (!append(&tail, a->data))
return 0;
a = a->next;
b = b->next;
}
}
return 1;
}
static int merge_difference(const struct Node *a, const struct Node *b, struct Node **out)
{
struct Node **tail = out;
*out = NULL;
while (a != NULL && b != NULL) {
if (a->data < b->data) {
if (!append(&tail, a->data))
return 0;
a = a->next;
} else if (b->data < a->data) {
b = b->next;
} else {
a = a->next;
b = b->next;
}
}
return append_rest(&tail, a);
}
static void print_list(const char *label, const struct Node *head)
{
printf("%s: ", label);
for (const struct Node *t = head; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
static void free_list(struct Node *head)
{
while (head != NULL) {
struct Node *next = head->next;
free(head);
head = next;
}
}
/* Reads a count, then that many integers; duplicates are skipped. */
static int read_list(const char *name, struct Node **head)
{
int n, value;
fprintf(stderr, "Number of elements in %s: ", name);
if (scanf("%d", &n) != 1 || n < 0)
return 0;
fprintf(stderr, "Enter %d integers: ", n);
for (int i = 0; i < n; i++)
if (scanf("%d", &value) != 1 || insert_sorted(head, value) < 0)
return 0;
return 1;
}
int main(void)
{
struct Node *a = NULL, *b = NULL, *u = NULL, *in = NULL, *d = NULL;
int ok = read_list("A", &a) && read_list("B", &b)
&& merge_union(a, b, &u) && merge_intersection(a, b, &in)
&& merge_difference(a, b, &d);
if (ok) {
print_list("A", a);
print_list("B", b);
print_list("Union", u);
print_list("Intersection", in);
print_list("A - B", d);
} else {
fprintf(stderr, "Error: bad input or out of memory\n");
}
free_list(a);
free_list(b);
free_list(u);
free_list(in);
free_list(d);
return ok ? 0 : 1;
}
Input: n, then n integers for A; m, then m integers for B, for example 5 1 2 3 4 5 4 4 5 6 7. Prompts go to stderr and the lists to stdout. Compiled with cc -std=c11 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined; 126, 144 and 169 lines.
The complete C program: queue.c
/* A queue in C using a linked list: enqueue at the rear, dequeue at the front.
Commands on stdin, one per line:
E x enqueue x D dequeue P peek S show
Prompts go to stderr and results to stdout, so the output can be compared. */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Queue {
struct Node *front; /* the next node to leave */
struct Node *rear; /* the last node in; NULL when the queue is empty */
};
static int enqueue(struct Queue *q, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL)
return 0;
node->data = value;
node->next = NULL;
if (q->rear == NULL)
q->front = node; /* empty queue: the node is front and rear */
else
q->rear->next = node;
q->rear = node;
return 1;
}
/* Returns 1 and stores the value, or 0 if the queue is empty. */
static int dequeue(struct Queue *q, int *value)
{
struct Node *old = q->front;
if (old == NULL)
return 0;
*value = old->data;
q->front = old->next;
if (q->front == NULL)
q->rear = NULL; /* the queue is empty again: without this,
rear points at the node freed below */
free(old);
return 1;
}
static int peek(const struct Queue *q, int *value)
{
if (q->front == NULL)
return 0;
*value = q->front->data;
return 1;
}
static void show(const struct Queue *q)
{
printf("Queue: ");
for (const struct Node *t = q->front; t != NULL; t = t->next)
printf("%d -> ", t->data);
printf("NULL\n");
}
int main(void)
{
struct Queue q = { NULL, NULL };
char cmd;
int value, ok = 1;
fprintf(stderr, "Commands: E x, D, P, S\n");
while (ok && scanf(" %c", &cmd) == 1) {
if (cmd == 'E') {
if (scanf("%d", &value) != 1 || !enqueue(&q, value))
ok = 0;
} else if (cmd == 'D') {
if (dequeue(&q, &value))
printf("Dequeued %d\n", value);
else
printf("Queue is empty\n");
} else if (cmd == 'P') {
if (peek(&q, &value))
printf("Front %d\n", value);
else
printf("Queue is empty\n");
} else if (cmd == 'S') {
show(&q);
} else {
ok = 0;
}
}
if (!ok)
fprintf(stderr, "Error: bad input or out of memory\n");
while (dequeue(&q, &value))
;
return ok ? 0 : 1;
}
How do you find the union and intersection of two linked lists in C?
Walk one list and, for each node, search the other. For the union, copy every node of list A into a new result list, then add each value of B that is not already there. For the intersection, walk A and add each value that a search of B finds. Each search is a while (t != NULL) loop that returns 1 on a match and 0 after the loop.
That is the method in 87% of the reports with text (737 of 844). The commonest function names are push, isPresent, getUnion, getIntersection and printList, each in about 250 reports. The second method keeps both lists sorted. Then the smaller of the two front values is always the next one to place, and a single pass down both lists builds the union, the intersection or the difference.
- As most reports do it: insert at the head, copy list A into the union without a check, search the result for each value of B, and walk A searching B for the intersection.
- Set-correct: insert refuses a value that is already in the list, so A and B are sets; results are appended at the tail and keep the input order. Still n × m comparisons.
- Sorted merge: insert puts each value in sorted position and refuses repeats; union, intersection and difference each take one pass, at most n + m − 1 comparisons.
Why does the union print in a different order from the input?
Because push puts every new node at the head. Read A = 1 2 3 4 5 with push and the list holds 5 → 4 → 3 → 2 → 1 → NULL: it prints backwards. The union then pushes A's nodes again, which reverses them back, and pushes B's new values in front. So for B = 4 5 6 7 the usual program prints 6 7 1 2 3 4 5: B's new values first, then A in the order you typed it.
We confirmed this by compiling three public reports' functions unchanged and running them. A set has no order, so the answer is still correct. The set-correct and sorted programs append at the tail and print 1 2 3 4 5 6 7. Inserting at the head costs O(1). Appending costs O(1) too if you keep a pointer to the last node, as the programs here do.
Does the usual union give a set? Not when list A has a repeat
The union copies list A with no membership check. If A holds a value twice, the union does too. Run A = 1 2 2 3 and B = 2 3 4 through the report method and the union is 4 1 2 2 3, the intersection 2 2 3. Neither is a set. Values repeated in B are dropped, because each value of B is searched for in the result built so far: A = 1 and B = 5 5 6 give 5 6 1.
659 of 844 reports copy list 1 into the union unchecked, and 607 add every intersection match without checking for a repeat. Another 185 search B's values in list 1 instead of the result, so a value repeated in B is added twice too. Only 12 make insert refuse a repeat. That one change keeps A and B sets, and both operations come out right.
What is the time complexity of union and intersection of linked lists?
O(n × m) with a search per node, O(n + m) by sorted merge. These are exact comparison counts from the lib, for two lists of n values each. "Worst case" is A = 1, 3, 5, … and B = 2, 4, 6, …: nothing in common, so every search runs to NULL. "Random" draws n different values from 1 to 2n for each list (seed 20261124), so about half are shared.
| n = m | Data | Union, report method | Union, set-correct | Intersection, set-correct | Union or intersection, merge | Building both sorted lists |
|---|---|---|---|---|---|---|
| 10 | worst | 145 | 100 | 100 | 19 | 90 |
| 100 | worst | 14,950 | 10,000 | 10,000 | 199 | 9,900 |
| 1,000 | worst | 14,99,500 | 10,00,000 | 10,00,000 | 1,999 | 9,99,000 |
| 10,000 | worst | 14,99,95,000 | 10,00,00,000 | 10,00,00,000 | 19,999 | 9,99,90,000 |
| 10 | random | 105 | 84 | 79 | 13 | 54 |
| 100 | random | 10,070 | 7,426 | 7,554 | 151 | 5,243 |
| 1,000 | random | 10,05,835 | 7,51,841 | 7,51,001 | 1,501 | 4,92,867 |
| 10,000 | random | 9,96,00,497 | 7,48,11,564 | 7,51,01,078 | 14,989 | 5,00,10,116 |
In plain words: at 10,000 nodes the nested search makes 10,00,00,000 comparisons in the worst case and 7,48,11,564 on random data. The merge makes 19,999 and 14,989. The report method's union is slower still (14,99,95,000), because it searches a result that keeps growing.
There is a catch. The merge needs sorted lists, and inserting each value into its place in a sorted linked list is O(n²) as well: 9,99,90,000 comparisons to build the two lists from ascending input, 5,00,10,116 from random input. Refusing repeats on insert costs the same. The merge wins when the lists are sorted once and combined many times, or when you sort them with merge sort, which needs O(n log n). A hash set gives expected O(n + m), as GeeksforGeeks notes, but C has no hash set in its standard library.
What the 920 reports do
Skill-Lync read the text of all 920 public reports for these two projects on 24 Nov 2026: 903 for the Sets project and 17 for the queue. 60 are image-only (fewer than 30 lines of their own text), leaving 860. Most counts below are out of the 844 Sets reports with text, as of 24 Nov 2026. Code that only appears in screenshots is not counted, so every count is a floor.
| What the code does | Reports | Examples |
|---|---|---|
| Find union and intersection by searching the other list for every node (nested search) O(n x m) comparisons; search helper usually named isPresent, search or compare | 737 of 844 | 123 |
| Use a sorted merge (walk both lists once, compare data with <) text after a < sign is missing from about 200 public pages, so this is a floor | 8 of 844 | 123 |
| Store the sets in arrays, with no linked list at all | 9 of 844 | 123 |
| Build the union by inserting each new node at the head (new->next = head; head = new) head insertion reverses the order of whatever it copies | 628 of 844 | 123 |
| Build the union by appending at the tail | 59 of 844 | 123 |
| Copy list 1 into the union with no membership check a value repeated inside list 1 is repeated in the union | 659 of 844 | 123 |
| Check list 2 values against list 1, not against the union being built a value repeated inside list 2 (and absent from list 1) is added twice | 185 of 844 | 123 |
| Intersection adds every match without checking the result for duplicates a value repeated in list 1 that is in list 2 appears twice | 607 of 844 | 123 |
| Insert refuses a value already in the list (each list stays a set) | 12 of 844 | 123 |
| Call free() anywhere the rest never release the nodes they malloc | 44 of 844 | 123 |
| Check the malloc result for NULL | 23 of 844 | 123 |
| Read the list length n from the user, then n values | 673 of 844 | 123 |
| Hard-code the list values as insert calls in main (no input) | 106 of 844 | 123 |
| Read a fixed number of values into separate variables (scanf into a, b, c, d) list size cannot change without editing the code | 25 of 844 | 123 |
| Keep the list head pointers as globals (file-scope Node* variables) | 204 of 844 | 123 |
| Implement any operation beyond insert, display, union and intersection mostly delete/remove (14) and sorting (8) | 27 of 844 | 123 |
| Implement delete / remove of an element | 14 of 844 | 123 |
| Sort a list (or insert in sorted order) | 8 of 844 | 123 |
| Show a program run as text (prompts and printed lists) many more show the run only as a screenshot | 102 of 844 | 123 |
| Of those showing a run: a printed list comes out in the reverse of the order typed the effect of head insertion, visible in their own output | 9 of 102 | 123 |
Only 8 use a sorted merge, 44 call free anywhere and 23 check malloc for NULL. 80% read the list length from the user, as the program here does.
Common slips in linked list set programs, and the fix for each
- A search function with no
return 0after the loop. When the value is absent, the function reaches its closing brace. C11 6.9.1p12: "If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined." The caller can get any value, so a missing element may be reported as found. Fix:return 0;after the loop. Clang warns about this by default ("non-void function does not return a value in all control paths"); do not ignore the warning. - Duplicates in the union or intersection. Explained above. Fix: make insert refuse repeats, or search the result before every insert.
mallocnot checked. C11 7.22.3.4: "The malloc function returns either a null pointer or a pointer to the allocated space." Writingnew_node->datathrough a null pointer is undefined behaviour and usually a crash. Fix:if (node == NULL) return 0;and pass the failure up, as the programs here do.- Nodes never freed. 800 of 844 reports show no call to
free. The operating system takes the memory back when the program ends, but on a microcontroller that runs for months the same habit runs it out of heap. Fix: afree_listthat savesnextbefore freeing each node. Every program on this page frees all its nodes, checked with macOSleaks. scanf's return value ignored. C11 7.21.6.2p16:fscanfreturns "the number of input items assigned, which can be fewer than provided for, or even zero". Type a letter and the loop reads garbage. Fix:if (scanf("%d", &n) != 1)stop with an error.- Fixed-size input. 25 reports read exactly four values into
a, b, c, d, and 106 hard-code the lists aspushcalls. Fix: read n first, then loop n times.
Queue using a linked list: why does rear need resetting?
A linked queue keeps two pointers: front, where nodes leave, and rear, where they join. When dequeue removes the last node, front becomes NULL. If rear is not set to NULL too, it still points at the node that was just freed. The next enqueue sees that rear is not NULL, writes rear->next into freed memory and leaves front at NULL.
Run E 10 E 20 D D E 30 P S with the box ticked in the Queue tab: the peek after enqueueing 30 says "Queue is empty", and 30 is lost. Compiled with AddressSanitizer, the program stops at that write with heap-use-after-free; we checked this by deleting the reset line from queue.c. With the line in place it prints "Front 30", "Queue: 30 -> NULL".
How the C programs were tested
Each program is compiled with -std=c11 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined -fno-sanitize-recover=undefined -g (Apple clang version 15.0.0 (clang-1500.0.40.1)) and run on the same 246 inputs the lib is checked against. They include empty lists, identical and disjoint lists, all duplicates, negative numbers, INT_MIN and INT_MAX, single elements and two 1,000-value lists. The printed lists match a separate Python model, values and order, in all 943 runs, with 0 sanitizer reports.
Apple's clang does not support LeakSanitizer on this Mac, so a plain build of each program was also run under leaks --atExit (56 runs): 0 leaks. Each also rejects a letter or a short input with exit status 1.
A linked list set is the first project of Skill-Lync's Embedded Programming Essentials course. The same pointer and memory habits (check every malloc, free what you allocate, never use a pointer to a freed node) are what firmware interviews probe.
Frequently asked questions
How do you find the union of two linked lists in C?
Copy every node of the first list into a new result list, then walk the second list and add each value the first list does not hold. Searching for each value costs up to n × m comparisons. If both lists are kept sorted, one merge pass does it in at most n + m − 1.
Why is my union printed in reverse order?
Because push() inserts each node at the head, so a list read with push prints backwards. The union pushes A's nodes again, restoring their order, and puts B's new values in front: A = 1 2 3 and B = 2 3 4 give 4 1 2 3. A set has no order, so that is correct.
What is the time complexity of union and intersection of two linked lists?
With a search of the other list for every node, both are O(n × m): 10,00,00,000 comparisons for two 10,000-node lists with nothing in common. Sorted lists need one merge pass, O(n + m), here 19,999 comparisons. Keeping a linked list sorted on insert is itself O(n²), so sort it with merge sort instead.
How do you remove duplicates when finding the union of linked lists?
Make insert refuse a value that is already in the list, so each input list is a set. Then copy list A and add only those values of B that are not in A. If you keep the usual push-everything code, check the result before every insert, including the values copied from list A.
Does the union of two linked lists have to keep the input order?
No. A set has no order, so 6 7 1 2 3 4 5 and 1 2 3 4 5 6 7 are the same union. What must hold is that every value of A or B appears exactly once. The check tab on this page reads your printed output and tells you which of those holds.
Queue using a linked list: why does rear need resetting?
When dequeue removes the last node, front becomes NULL but rear still points at the node just freed. The next enqueue sees rear is not NULL, writes rear->next into freed memory and never sets front, so the new value is lost. Setting rear = NULL when front becomes NULL fixes it.
Is it a bug if my search function has no return 0 at the end?
Yes. If the loop finishes without finding the value, the function reaches its closing brace without returning anything. The C11 standard says using that value is undefined behaviour (6.9.1, paragraph 12). It may seem to work on one compiler and fail on another, so always end with return 0.
Related on Skill-Lync
- MC/DC coverage calculator: test cases for the decisions in your C code
- Landing gear state machine: Project 2 of the same course, with a checker for your C state machine
- I2C calculator and Arduino sketch checker
- AVR PWM calculator
- Student project: union and intersection with linked lists
- Embedded systems courses compared
- All free engineering tools
Sources
- ISO/IEC 9899:201x, committee draft N1570 (12 April 2011, the C11 text): 6.9.1p12 (reaching the closing brace of a function), 7.21.6.2p16 (what
fscanfreturns), 7.22.3.3p2 (free), 7.22.3.4p3 (mallocmay return a null pointer). - Clang AddressSanitizer documentation, "Memory leak detection" and "Supported Platforms"; Apple
leaks(1)manual,-atExit. - GeeksforGeeks, "Union of two Linked Lists": the two nested loops method, O(n × m), and hashing, O(n + m).
- Skill-Lync course pages: Embedded Programming Essentials, project "User Interfaces for Working with Sets"; Accelerated Career Program in Embedded Systems, "Implement a fully-functional Queue in C language using Linked lists".
- Skill-Lync, all 920 public reports of the two projects, read 24 Nov 2026; three reports' functions compiled unchanged to confirm the order and duplicate behaviour. scripts/verify/linked_list_set.py re-derives every list and count with its own Python linked list and cost formulas, and compiles and runs the C programs (20,614 checks); the page checks itself against it at build time (32,272 comparisons).