Black FridayUpgrade your career this Black Friday. Get up to ₹60,000 Scholarship on IIT programsUp to ₹60K Black Friday Scholarship63 seats leftOffer ends Fri, 27 Nov, 11:59 pm IST.

Black Friday Scholarship – IIT Jammu & IIT Roorkee

The best Black Friday deal isn't a gadget. It's your next career move.

Get up to ₹60,000 Black Friday Scholarship on our PG programs with IIT Jammu and iHUB DivyaSampark, IIT Roorkee. IIT certification, 12 live sessions with IIT faculty and 100% placement assistance.

Only 63 seats left. Offer ends Fri, 27 Nov, 11:59 pm IST

3,905 engineers placed since 2019 · 1,276 hiring companies

By submitting you agree to our Terms and Privacy Policy.

Your free demo class is requested

Browse courses

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.

Comparisons24
malloc calls7
free calls0
A54321NULLB7654NULLresult6712345NULLresult

done: 7 nodes in the result

step 46 of 46

Result in linked order
6 → 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.

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;
}

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.

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 = mDataUnion, report methodUnion, set-correctIntersection, set-correctUnion or intersection, mergeBuilding both sorted lists
10worst1451001001990
100worst14,95010,00010,0001999,900
1,000worst14,99,50010,00,00010,00,0001,9999,99,000
10,000worst14,99,95,00010,00,00,00010,00,00,00019,9999,99,90,000
10random10584791354
100random10,0707,4267,5541515,243
1,000random10,05,8357,51,8417,51,0011,5014,92,867
10,000random9,96,00,4977,48,11,5647,51,01,07814,9895,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 doesReportsExamples
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 844123
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 844123
Store the sets in arrays, with no linked list at all9 of 844123
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 844123
Build the union by appending at the tail59 of 844123
Copy list 1 into the union with no membership check
a value repeated inside list 1 is repeated in the union
659 of 844123
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 844123
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 844123
Insert refuses a value already in the list (each list stays a set)12 of 844123
Call free() anywhere
the rest never release the nodes they malloc
44 of 844123
Check the malloc result for NULL23 of 844123
Read the list length n from the user, then n values673 of 844123
Hard-code the list values as insert calls in main (no input)106 of 844123
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 844123
Keep the list head pointers as globals (file-scope Node* variables)204 of 844123
Implement any operation beyond insert, display, union and intersection
mostly delete/remove (14) and sorting (8)
27 of 844123
Implement delete / remove of an element14 of 844123
Sort a list (or insert in sorted order)8 of 844123
Show a program run as text (prompts and printed lists)
many more show the run only as a screenshot
102 of 844123
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 102123

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 0 after 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.
  • malloc not checked. C11 7.22.3.4: "The malloc function returns either a null pointer or a pointer to the allocated space." Writing new_node->data through 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: a free_list that saves next before freeing each node. Every program on this page frees all its nodes, checked with macOS leaks.
  • scanf's return value ignored. C11 7.21.6.2p16: fscanf returns "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 as push calls. 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.

Learn embedded C

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

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 fscanf returns), 7.22.3.3p2 (free), 7.22.3.4p3 (malloc may 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).
Free counselling

From a linked list project to a firmware job.

Pointers, memory and data structures in C are the first thing embedded interviews test. A Skill-Lync counsellor can map the embedded course that fits the role you want.

Talk to a course counsellor

Free. We call you back, usually the same day.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.