How to Create Linked List in C- Free C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union · Lecture 34

Create Linked List in C

Build a singly linked list from input, then combine create, insert, delete and search into one complete command-driven C program you can run and pipe test data into.

In this lecture of the free C programming course we finally put everything together. You will learn how to create a linked list in C from a stream of values, and then wrap the insertion and deletion routines from the last three lectures inside one program that behaves like a tiny console tool. This free C tutorial also introduces a trick that makes creation O(n) instead of O(n squared), the “next free slot” pointer, which is a favourite in embedded C programming interviews. By the end you will have a reusable skeleton for any list-based menu, command parser or test harness.

What You Will Learn

  • How list creation is just repeated insertion at the end
  • Why naive creation is slow and how a tail slot pointer fixes it
  • How to design a program around a small command loop
  • How to implement search that returns a position
  • How to test a console program without typing, by piping a script into it

Prerequisites

Complete the insertion and deletion lectures first. You need push_front(), append(), insert_after(), delete_value() and free_list(). A basic grasp of scanf() and the switch statement from earlier chapters of this free embedded C course is enough for the rest.

How to Create a Linked List in C

Creation has no magic. An empty list is a head pointer set to NULL. Creating a list of five values means making five nodes and attaching each to the end of the growing chain. The first node is the only one that touches the head; every later node attaches to the previous node’s next. You can express that with an if (head == NULL) branch, or you can avoid the branch entirely, as we show below.

The slow way and the fast way

If you call append() in a loop, every call walks the whole list again. Building n nodes costs 1 + 2 + 3 + … + n steps, roughly n squared over two. For ten nodes you will not notice. For ten thousand sensor samples on a slow microcontroller you will.

TechniquePer nodeTotal for n nodesExtra state
append() in a loopO(n) walkO(n squared)None
Tail pointer (node)O(1)O(n)One pointer, plus a first-node branch
Next-free-slot pointerO(1)O(n)One pointer-to-pointer, no branch

The slot pointer tail is of type node_t **. It always holds the address of the place where the next node should be stored. At the start that place is the head variable itself. After storing a node there, move the slot to that node’s own next field. Because the slot always points at a spot that is currently NULL, storing a node is the single line *tail = n.

The tail slot always marks the next empty place

starttail→ slot: head (empty)
after 10head→10 | nexttail→ 10’s next slot (empty)
after 20head→10 | next→20 | nexttail→ 20’s next slot (empty)

Designing the Menu-Driven Linked List Program

Instead of printing a seven-line menu and waiting for a number every loop, we design a command language: one letter followed by its arguments. That makes the program equally easy to use by hand and to automate in a test. Each command calls exactly one function from the earlier lectures.

CommandArgumentsAction
ccount v1 … vcountCreate: discard old list, build new one
fvalueInsert at beginning
avalueAppend at end
ikey valueInsert value after the node holding key
dvalueDelete first node holding value
svalueSearch, print the zero-based position
pnonePrint the list
qnoneQuit

Program flow

read command letter→switch on letter→read its arguments→call list function→loop back
q or end of input→free_list(head)→exit

Complete Create and Manage Linked List Program

Read it in this order: node helpers, search(), create_list() with the slot pointer, and finally main(). Note that create_list() frees the old list first, so choosing c twice does not leak. Also note that main() checks the return value of scanf() every time; if the input ends early the loop simply stops.

#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)
{
    if (head == NULL) {
        printf("(empty)\n");
        return;
    }
    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 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;
}

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

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;
    prev->next = n;
    return 0;
}

static int delete_value(node_t **head, int key)
{
    for (node_t **pp = head; *pp != NULL; pp = &(*pp)->next) {
        if ((*pp)->value == key) {
            node_t *dead = *pp;
            *pp = dead->next;
            free(dead);
            return 0;
        }
    }
    return -1;
}

/* position of key (0-based) or -1 */
static int search(const node_t *head, int key)
{
    int pos = 0;
    for (const node_t *p = head; p != NULL; p = p->next, pos++)
        if (p->value == key)
            return pos;
    return -1;
}

/* discard the old list and build a new one from stdin values */
static node_t *create_list(node_t *old, int count)
{
    free_list(old);
    node_t *head = NULL;
    node_t **tail = &head;           /* always points at the NEXT free slot */
    for (int i = 0; i < count; i++) {
        int v;
        if (scanf("%d", &v) != 1)
            break;
        node_t *n = make_node(v);
        if (n == NULL)
            break;
        *tail = n;
        tail = &n->next;
    }
    return head;
}

int main(void)
{
    node_t *head = NULL;
    char cmd;

    while (scanf(" %c", &cmd) == 1 && cmd != 'q') {
        int a, b;
        switch (cmd) {
        case 'c':
            if (scanf("%d", &a) == 1)
                head = create_list(head, a);
            break;
        case 'f':
            if (scanf("%d", &a) == 1)
                push_front(&head, a);
            break;
        case 'a':
            if (scanf("%d", &a) == 1)
                append(&head, a);
            break;
        case 'i':
            if (scanf("%d %d", &a, &b) == 2 &&
                insert_after(find(head, a), b) != 0)
                printf("key %d not found\n", a);
            break;
        case 'd':
            if (scanf("%d", &a) == 1 && delete_value(&head, a) != 0)
                printf("key %d not found\n", a);
            break;
        case 's':
            if (scanf("%d", &a) == 1) {
                int pos = search(head, a);
                if (pos >= 0)
                    printf("%d found at position %d\n", a, pos);
                else
                    printf("%d not found\n", a);
            }
            break;
        case 'p':
            print_list(head);
            break;
        default:
            printf("unknown command '%c'\n", cmd);
        }
    }

    free_list(head);
    return 0;
}

Build and run with a test script

Save the following commands in a file called cmds.txt. They create 10, 20, 30, 40; print; push 5; append 50; print; insert 25 after 20; try an insert after a missing key; search for 30 and for 77; delete 5, 50 and a missing 88; print; recreate an empty list; print; quit.

c 4 10 20 30 40
p
f 5
a 50
p
i 20 25
i 99 1
s 30
s 77
d 5
d 50
d 88
p
c 0
p
q
gcc -std=c11 -Wall -Wextra -g -fsanitize=address,undefined -o ll_menu ll34.c
./ll_menu < cmds.txt

Expected output:

10 -> 20 -> 30 -> 40 -> NULL
5 -> 10 -> 20 -> 30 -> 40 -> 50 -> NULL
key 99 not found
30 found at position 4
77 not found
key 88 not found
10 -> 20 -> 25 -> 30 -> 40 -> NULL
(empty)

Checking the result

  • After the first p you see the four created values; after the second, 5 is in front and 50 at the back.
  • i 99 1 prints “key 99 not found” because 99 was never inserted, and the list is left unchanged.
  • s 30 reports position 4: at that moment the list is 5, 10, 20, 25, 30, 40, 50, so four nodes come before 30 (positions are zero-based).
  • The final c 0 frees everything and leaves an empty list, printed as “(empty)”.

Why a command script beats typing

Because the program reads from standard input, you can redirect a file into it. You get repeatable tests, you can add a failing case when you find a bug, and the same trick works for firmware command shells over UART.

Embedded C Programming Connection

A command parser plus a list of records is the skeleton of many embedded tools: a CLI over a serial port, a scheduler table, a log buffer. The difference on real hardware is where the nodes come from. A desktop program can call malloc() freely; a small microcontroller often cannot. The next lecture removes the heap entirely by building the same list from a static array of nodes.

Common Mistakes

MistakeResultFix
Not setting head to NULL before creatingGarbage head, crash on first printInitialise head = NULL and free the old list first
Ignoring scanf return valueInfinite loop on bad input or end of fileTest == 1 (or the expected count)
Using ” %c” without the leading spaceThe newline is read as a commandKeep the space before %c
Forgetting free_list() on exitLeak reported by the sanitizerFree in one place, at the end of main
Returning the slot pointer from a functionDangling pointer to a local variableKeep tail local to the building loop

Best Practices

  • Keep one function per list operation and let main() only dispatch.
  • Treat a failed malloc() as an expected event, not a crash.
  • Make output deterministic so tests can compare it to a saved file.
  • Free the list exactly once, at a single exit path.

Summary and Key Takeaways

  • Creating a list is repeated end insertion; a next-free-slot pointer makes it linear.
  • A command-driven main() is easy to use and easy to test.
  • Search is a simple walk that returns a position or -1.
  • Create frees the old list to avoid leaks.

This is the point where the free C programming course linked list chapter becomes a complete program. One lecture remains: an embedded lab, a quiz and interview questions.

Frequently Asked Questions

How do you create a linked list in C step by step?

Start with head = NULL, allocate a node for each value, and attach it to the end. A pointer-to-pointer slot makes this one line per node.

Why is a menu-driven program useful for learning linked lists?

It lets you try any sequence of operations and see the list after each, which makes pointer bugs visible quickly.

What does the p command print for an empty list?

The program prints “(empty)” so you can tell an empty list apart from one that only contains NULL output.

Can I read the commands from a file?

Yes. Use shell redirection such as ./ll_menu < cmds.txt, because the program reads from standard input.

Why use node_t ** for the tail in creation?

It points at the empty slot, either the head variable or a next field, so the code needs no first-node special case.

Is this free embedded C course suitable for beginners?

Yes. Each lecture explains the idea, shows a picture, then gives original code with expected output.

Almost Done with Linked Lists

The next lecture is a hands-on embedded lab followed by a quiz and interview questions.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →