What is Display Search Linked List- C Programming For Beginners

🚀 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 →

PREV_LEC | NEXT_LEC

Display Search Linked List

Free C programming course: traverse, print and search a singly linked list, free it safely, and run the complete menu program.

A list you cannot see is a list you cannot debug. In this lecture of our free C programming course we write the last functions of the linked list menu program: print_list() to display every element, find_position() to search for a value, and free_list() to return all memory when the program ends. Then we assemble everything into one complete, compiled and tested program. Traversal is the most reused skill in embedded C programming: scanning a list of registered callbacks, searching a table of device handles, or walking a chain of packet buffers all use the loop you will learn here. This is a practical part of our free embedded C course.

What You Will Learn

  • How list traversal works with a single moving pointer
  • Printing a list with the empty-list case handled cleanly
  • Searching a list and reporting a 1-based position
  • Why const pointers make read-only functions safer
  • Freeing every node without using a node after it is freed
  • The complete tested program and its expected output

Prerequisites

  • The previous two lectures on insertion and deletion
  • Pointers and the const keyword
  • Comfort with for loops that use pointers instead of counters

Traversal: One Pointer Walking the Chain

To visit every node you need only a pointer that starts at the head and moves to next until it becomes NULL. Nothing else is needed. The loop ends naturally because the last node’s next is NULL, so the end of the list marks itself.

Traversal visits each node once

Pass 1p→5→10→20→NULL
Pass 25→p10→20→NULL
Pass 35→10→p20→NULL
Stop5→10→20→p = NULL

Displaying the Linked List

Our display function takes a const struct node *. The const promises that the function will not modify any node, and the compiler enforces that promise. It also lets us advance the parameter head itself, because the parameter is a private copy. No extra variable is needed.

void print_list(const struct node *head)
{
    if (head == NULL) {
        printf("List is empty\n");
        return;
    }
    printf("List:");
    for (; head != NULL; head = head->next)
        printf(" %d", head->value);
    printf("\n");
}

Do not forget the empty-list message. A blank line is confusing: the user cannot tell whether the program crashed, hung or simply has nothing to show.

Searching the Linked List

A linear search compares each stored value with the one requested. The first match wins. We return the 1-based position because that is what a user counts, and we return 0 to mean “not found”. Zero is a safe sentinel because positions start at 1.

int find_position(const struct node *head, int value)
{
    int pos = 1;

    for (; head != NULL; head = head->next, pos++)
        if (head->value == value)
            return pos;
    return 0;
}
ListSearch valueReturnedPrinted message
5 10 15 3030430 found at position 4
5 10 15 30515 found at position 1
5 10 15 3077077 not in list
emptyany0any not in list

Search cost

A linked list cannot jump to the middle, so search is O(n). Binary search, which you studied with arrays, needs random access and does not work here. If you must search often, choose an array or a hash table; if you must insert and delete often, a linked list shines.

Freeing the Entire List

When the program ends, every node still in the list was allocated with malloc() and should be returned. Operating systems reclaim memory on exit, but good habits matter: in a long-running service or a test under valgrind, leaks show up as errors. The golden rule: read next before you free the node that holds it.

void free_list(struct node **head)
{
    struct node *next;

    while (*head != NULL) {
        next = (*head)->next;
        free(*head);
        *head = next;
    }
}

Free one node at a time

1save next = second node
2free(first node)
3head = saved next
4repeat until head is NULL
Classic bug: free(p); p = p->next; reads from freed memory. It may seem to work today and crash tomorrow. Save the next pointer first.

The Complete Menu Program

Here is the whole program in one file. Type it in yourself rather than pasting, and read every function once more as you do. It was compiled with gcc -std=c17 -Wall -Wextra with no warnings.

#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node *next;
};

static struct node *make_node(int value)
{
    struct node *n = malloc(sizeof *n);

    if (n == NULL)
        return NULL;
    n->value = value;
    n->next = NULL;
    return n;
}

int push_front(struct node **head, int value)
{
    struct node *n = make_node(value);

    if (n == NULL)
        return -1;
    n->next = *head;
    *head = n;
    return 0;
}

int push_back(struct node **head, int value)
{
    struct node *n = make_node(value);
    struct node *cur;

    if (n == NULL)
        return -1;
    if (*head == NULL) {
        *head = n;
        return 0;
    }
    cur = *head;
    while (cur->next != NULL)
        cur = cur->next;
    cur->next = n;
    return 0;
}

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

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

void print_list(const struct node *head)
{
    if (head == NULL) {
        printf("List is empty\n");
        return;
    }
    printf("List:");
    for (; head != NULL; head = head->next)
        printf(" %d", head->value);
    printf("\n");
}

int find_position(const struct node *head, int value)
{
    int pos = 1;

    for (; head != NULL; head = head->next, pos++)
        if (head->value == value)
            return pos;
    return 0;
}

void free_list(struct node **head)
{
    struct node *next;

    while (*head != NULL) {
        next = (*head)->next;
        free(*head);
        *head = next;
    }
}

static int ask(const char *prompt, int *out)
{
    printf("%s", prompt);
    return scanf("%d", out) == 1;
}

int main(void)
{
    struct node *head = NULL;
    int choice, value, pos;

    for (;;) {
        printf("\n1 Add front | 2 Add back | 3 Add after position\n");
        printf("4 Delete value | 5 Show | 6 Search | 0 Exit\n");
        if (!ask("Choice: ", &choice))
            break;
        if (choice == 0)
            break;
        switch (choice) {
        case 1:
            if (ask("Value: ", &value))
                push_front(&head, value);
            break;
        case 2:
            if (ask("Value: ", &value))
                push_back(&head, value);
            break;
        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;
        case 5:
            print_list(head);
            break;
        case 6:
            if (ask("Value to find: ", &value)) {
                pos = find_position(head, value);
                if (pos)
                    printf("%d found at position %d\n", value, pos);
                else
                    printf("%d not in list\n", value);
            }
            break;
        default:
            printf("Wrong choice\n");
        }
    }
    free_list(&head);
    return 0;
}

Build, Run and Expected Output

Compile and run the program. To test without typing every answer, feed the choices through a pipe. The sequence below adds 10, 20, 30 at the back, 5 at the front, shows the list, inserts 15 after position 2, deletes 20, then searches for 30.

gcc -std=c17 -Wall -Wextra -o list_menu list_menu.c
printf '2\n10\n2\n20\n2\n30\n1\n5\n5\n3\n15\n2\n5\n4\n20\n5\n6\n30\n0\n' | ./list_menu

The important lines of the output, in order:

Choice: List: 5 10 20 30
Choice: Value: After position:
Choice: List: 5 10 15 20 30
Choice: Value to delete:
Choice: List: 5 10 15 30
Choice: Value to find: 30 found at position 4

Prompts and the menu text appear between these lines because the program prints a menu every time. If your list after each step matches the lines above, every function in your program works.

Check for leaks

On Linux run valgrind --leak-check=full ./list_menu or compile with -fsanitize=address. A clean report means free_list() released every node.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Using while (p->next != NULL) to printLast node never printed, crash on empty listLoop on p != NULL
Returning 0 for both “found at first” and “not found”Wrong messagesCount positions from 1
Reading next after free()Random crashesSave next first
Calling exit() inside the switchCleanup skippedBreak out of the loop, then free
Leaving scanf uncheckedInfinite loop on bad inputTest its return value

Best Practices and Security

  • Mark read-only parameters const.
  • Check the return value of scanf(); unchecked input is a classic source of undefined behaviour.
  • Never trust a position from the user: validate it, as insert_after() does.
  • Free what you allocate on every exit path.
  • Keep the menu code separate from the list code so the list functions can be reused in other projects.

Key Takeaways

  • Traversal needs one pointer and the stop condition p != NULL.
  • Search is linear and returns a position, with 0 meaning absent.
  • Free a list by saving next before each free().
  • Test every operation on empty, single, and multi-node lists.

Conclusion

The menu-driven linked list is now complete: create, insert at three places, delete, display, search and clean up. In the next lecture we look at a very popular interview task, reversing a linked list, and see the idea before we write the code. Keep following this free C tutorial series to master C programming for embedded systems.

Frequently Asked Questions

Why does print_list take a const pointer?

It signals and enforces that printing never changes the list. The compiler reports an error if you accidentally modify a node.

Is it safe to modify the head parameter inside print_list?

Yes. The parameter is a copy of the caller’s pointer, so moving it does not affect the real head.

Why return 0 instead of -1 for not found in find_position?

Positions start at 1, so 0 can never be a valid answer. It is a convenient sentinel and works directly inside an if statement.

Do I really need free_list if the program is about to exit?

The operating system reclaims the memory, but freeing is a good habit and keeps leak-checking tools quiet, which helps you find real leaks.

Can I search a linked list faster than O(n)?

Not with a plain singly linked list. You can keep it sorted to stop early, or use another data structure.

Free C Programming Course for Embedded Developers

Next: the idea behind reversing a linked list.

PREV_LEC | NEXT_LEC

💬 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 →