What is Linked List Menu Program- C Programming Course Online

🚀 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

Linked List Menu Program

Part of our free C programming course for embedded systems: design a menu-driven linked list, create nodes safely, and add them at the front or the back.

If you are following this free C programming course, you already know self-referential structures, node traversal and the basic ideas of insertion. In this lecture we put those ideas together into one real program: a menu-driven linked list in C that a user can drive from the keyboard. This is the exact shape of code you meet in embedded C programming: a small command dispatcher on top of a dynamic data structure, such as a queue of pending sensor readings or a list of active timers.

This lecture is part of a free C tutorial series for students who want job-ready C programming for embedded systems. Every line of code here is original and compiled with gcc -std=c17 -Wall -Wextra.

What You Will Learn

  • How to design a menu-driven program around a switch inside an infinite loop
  • How to write a safe node-creation helper that checks malloc()
  • How to add a node at the front of a linked list in constant time
  • How to add a node at the end of a linked list by walking to the tail
  • Why passing struct node **head beats using a global pointer
  • Common beginner mistakes with the head pointer and how to avoid them

Prerequisites

  • Structures and the . and -> operators
  • Pointers, malloc(), free() and pointer to pointer
  • Functions, call by reference and the switch statement

Design of a Menu-Driven Linked List Program

A menu-driven program has three layers. The top layer is the loop that prints the menu and reads a choice. The middle layer is the switch that dispatches the choice to a function. The bottom layer is the set of small functions that actually change the list. Keeping these layers apart is the single most useful habit in C: when something breaks, you know exactly which layer to look at.

Three layers of the menu program

Layer 1main(): loop + print menu + read choice
Layer 2switch(choice): pick the operation
Layer 3push_front / push_back / insert_after / remove_value / print_list / find_position

Our program offers seven actions. We will build them over the next three lectures:

Menu choiceFunctionLecture
1 Add frontpush_front()This one
2 Add backpush_back()This one
3 Add after positioninsert_after()Next lecture
4 Delete valueremove_value()Next lecture
5 Showprint_list()Lecture after that
6 Searchfind_position()Lecture after that
0 Exitfree_list() then returnLecture after that

The Node and the Head Pointer

A linked list is nothing more than a chain of structures. Each structure stores one value and the address of the next structure. The list as a whole is represented by one pointer, the head, that holds the address of the first node. An empty list is simply a head equal to NULL.

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

A list of three nodes

head→value 10next→value 20next→value 30next = NULL

Why not a global head pointer?

Many older books keep the head in a global variable. It works for one list, but the functions can never be reused for a second list, and bugs become hard to trace. We pass the address of the head pointer instead, as struct node **head. The function can then change where the head points, which is what front insertion needs.

Creating a Node Safely

Every insertion starts with a new node. Instead of repeating malloc() in each function, we write one helper. It allocates, fills in the value, sets next to NULL and returns the pointer. If malloc() fails, it returns NULL and the caller must handle it. On a small microcontroller with a few kilobytes of heap, allocation failure is a real possibility, so ignoring it is not an option.

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

Notice sizeof *n instead of sizeof(struct node). If you later change the type of n, the size follows automatically. Always initialising next to NULL prevents the classic bug where a new node carries a garbage pointer.

Adding a Node at the Front

Front insertion is the cheapest operation on a singly linked list. You do not need to walk anywhere. Two pointer assignments are enough, and the order matters.

  1. Create the node.
  2. Make the new node’s next point to the current first node.
  3. Make head point to the new node.

Front insertion: before and after

Beforehead→10→20→NULL
Step 2new 5→10→20→NULL
Afterhead→5→10→20→NULL
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;
}

This code also works when the list is empty. Then *head is NULL, so the new node’s next becomes NULL and the node becomes the only element. There is no special case to write.

Order matters. If you write *head = n; first, you lose the address of the old first node and the whole old list leaks. Always connect the new node to the old list before you move the head.

Adding a Node at the End

To add at the back, we must find the last node, the one whose next is NULL, and attach the new node there. That requires walking the list, so the cost grows with the length: it is an O(n) operation. There are two cases: the list is empty, or it is not.

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

Walking to the tail

cur at start10→20→30→NULL
cur stops at 3030 next = NULL→ attachnew 40
OperationNeeds a walk?CostSpecial case
Add at frontNoO(1)None
Add at backYes, to the tailO(n)Empty list

Building the Menu Loop

With the two functions ready, here is the skeleton of main(). A small helper ask() prints a prompt and reads one integer. It returns zero when input fails, which lets the program stop cleanly at end of input instead of looping forever on bad data.

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;

    for (;;) {
        printf("\n1 Add front | 2 Add back | 0 Exit\n");
        if (!ask("Choice: ", &choice) || 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;
        default:
            printf("Wrong choice\n");
        }
    }
    return 0;
}

Pay attention to the default label. Without it, a typo such as 9 would silently do nothing and confuse the user. Notice also that the loop leaves with break rather than calling exit() inside the switch; that way cleanup code placed after the loop always runs. We add that cleanup, free_list(), in a later lecture.

Real-World Use in Embedded Systems

  • Event queues: new events are added at the back, handled from the front.
  • Timer lists: a software timer module keeps active timers in a linked list and inserts new ones.
  • Command history: a serial console keeps recent commands, newest at the front.
  • Driver bookkeeping: device lists in the Linux kernel use the same idea in the form of list_head.

Embedded tip

Many safety-critical embedded projects forbid malloc() after start-up. The pointer logic you learn here is identical when nodes come from a fixed static array, and we have seen that approach in an earlier lab. Learn the logic once, then choose the memory source that fits your target.

Common Mistakes and Troubleshooting

MistakeSymptomFix
Passing head by value to push_front()List stays empty after insertPass &head and take struct node **
Not setting next = NULL in the new nodeCrash when walking the listInitialise in make_node()
Skipping the empty-list case in push_back()Segmentation fault on first insertTest *head == NULL first
Ignoring a NULL from malloc()Crash under low memoryReturn an error code and check it
Moving head before linking the new nodeOld nodes lost (memory leak)Link first, then move head

Best Practices

  • One small function per operation, one job each.
  • Return a status code from every function that can fail.
  • Prefer sizeof *pointer over sizeof(type).
  • Compile with -Wall -Wextra and test with valgrind or -fsanitize=address.
  • Test the empty list, one node, and many nodes every time.

Build and Run

gcc -std=c17 -Wall -Wextra -o list_menu list_menu.c
./list_menu

Sample session using only choices 1 and 2: add 10 at the back, add 20 at the back, then add 5 at the front. Once the display function arrives, the list will read 5 10 20.

Key Takeaways

  • A linked list is a head pointer plus nodes that point to each other.
  • Front insertion is O(1); back insertion needs a walk and is O(n).
  • Pass the address of the head when a function may change it.
  • Always check malloc() and always initialise next.

Conclusion

You now have the skeleton of a menu-driven linked list: a clean three-layer design, a safe node factory, and the two simplest insertions. In the next lecture we add the more delicate operations, inserting after a given position and deleting a node, where pointer order and edge cases decide whether your program works. Keep following this free embedded C course to turn these ideas into confident, interview-ready skills.

Frequently Asked Questions

Why is front insertion faster than back insertion?

Front insertion only needs the head pointer, so it takes a fixed number of steps. Back insertion must walk to the last node first, so the time grows with the list length.

Why do we pass struct node ** instead of struct node *?

C passes arguments by value. A function that receives a copy of the head cannot change the caller’s head. Passing its address lets the function update it.

Can I keep a tail pointer to make back insertion O(1)?

Yes. Many queue implementations store both head and tail. The cost is extra bookkeeping on deletion.

What happens if malloc returns NULL?

No node is created. Our helper returns NULL and the insert function returns an error so the program can report it instead of crashing.

Is a linked list a good choice for embedded systems?

It is useful when the number of items changes at run time, but each node costs extra memory for the pointer, and heap use may be restricted. Fixed arrays or static pools are often preferred in small devices.

Is this course really free?

Yes. This free C programming course and the related free embedded systems and Linux courses on EmbeddedPathashala are open to every student.

Continue the Free C Programming Course

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 →