TalentJR

⚙️ C programming basics · Class 10 · Lesson 13 of 18 · Free

Linked Lists in C – Build a Chain of Nodes with malloc

⏱ About 40 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Define a node struct and walk a linked list from head to NULL
  • Insert nodes at the front, at the end and in sorted order with malloc
  • Delete a node and free the whole list without losing memory

A train is not one long box. It is coaches joined by couplings: each coach only knows the next one. To add a coach you just couple it on, and nothing else moves. A linked list stores data the same way, and in this lesson you build one with malloc from Lesson 7.

What is a linked list in C?

A linked list is a chain of nodes. Each node is a struct with some data and a pointer to the next node. The last node's pointer is NULL, which means "end of the chain".

The program only keeps a pointer to the first node, called the head. To visit every node, start at head and follow next until you reach NULL.

Here three coaches are made as plain variables and joined by hand. Try it: make a fourth coach "S3", join it after s2 and run again.

⚙️ C — you can edit this code
Output
[ENGINE] -> [S1] -> [S2] -> NULL

💡 p->name is short for (*p).name: the member of the struct that p points to (Lesson 4).

How do you insert a node at the beginning of a linked list in C?

Real lists grow while the program runs, so each node is made with malloc (Lesson 7). Adding at the front is the easiest: the new node points to the old head, and then becomes the head.

The function must change main's head variable. So we pass the ADDRESS of head: a pointer to a pointer, `struct Node **head`.

When you are done, free every node. Save next BEFORE you free a node, because after free you may not touch it. Try it: push 40 as well.

⚙️ C — you can edit this code
Output
10 -> 20 -> 30 -> NULL

How do you add a node at the end of a linked list?

A queue of library books should keep the order they were returned. So new nodes go at the end.

To find the end, walk until a node's next is NULL. An empty list is a special case: the new node becomes the head.

Walking the whole list takes longer as it grows. Big programs keep a tail pointer too, so adding at the end is instant. Try it: append a fourth book.

⚙️ C — you can edit this code
Output
1. Panchatantra
2. Wings of Fire
3. Malgudi Days

How do you insert into a sorted linked list in C?

Here is where a linked list beats an array. To put a new score in the middle of an array you must shift everything after it. In a list you just change two pointers.

The trick: walk with a pointer to the `next` field (`struct Node **link`). Stop at the first node with a smaller score, and link the new node in there.

This keeps a cricket leaderboard sorted from the highest score down. Try it: add a score of 100.

⚙️ C — you can edit this code
Output
82 60 45 17 

How do you delete a node from a linked list in C?

To delete, make the link that points to the node skip over it. Then free the node.

The same `struct Node **link` trick handles the head too, so you need no special case for the first node.

The function returns 1 if it found and deleted the roll number, else 0. Try it: delete 7, which is the head.

⚙️ C — you can edit this code
Output
Absent list: 7 14 21
Delete 14: done
Delete 99: not found
Absent list: 7 21

💡 A student who came late is removed from the absent list: one pointer change, no shifting.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. 1, 2 and 3 are pushed to the FRONT. What does this print?

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

struct Node { int data; struct Node *next; };

void push_front(struct Node **head, int v) {
    struct Node *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->data = v;
    n->next = *head;
    *head = n;
}

int main(void) {
    struct Node *head = NULL;
    for (int i = 1; i <= 3; i++) push_front(&head, i);
    for (struct Node *p = head; p; p = p->next) printf("%d ", p->data);
    printf("\n");
    while (head) { struct Node *t = head->next; free(head); head = t; }
    return 0;
}

Question 2. What does this print?

struct N { int data; struct N *next; };
struct N c = { 30, NULL };
struct N b = { 20, &c };
struct N a = { 10, &b };
printf("%d\n", a.next->next->data);

Question 3. The loop condition is p->next != NULL. What does this print?

struct N { int data; struct N *next; };
struct N c = { 30, NULL };
struct N b = { 20, &c };
struct N a = { 10, &b };
for (struct N *p = &a; p->next != NULL; p = p->next) printf("%d ", p->data);
printf("\n");

🧩 Your challenge

Make a waiting list for the school library. Read names until the word "end" and append each name at the END of a linked list. Then print the list with numbers, read one more name and print its position (or "not in the list"). Free the list at the end. Example for inputs Asha, Ravi, Meena, end, Ravi: 1. Asha 2. Ravi 3. Meena Ravi is number 2 in the list

Expected output (with the inputs given):
Name (or end): Asha
Name (or end): Ravi
Name (or end): Meena
Name (or end): end
1. Asha
2. Ravi
3. Meena
Search for: Ravi
Ravi is number 2 in the list
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

struct N { int data; struct N *next; };
struct N b = { 20, NULL };
struct N *p = &b;
printf("%d\n", p.data);

Line 4: error: member reference type 'struct N *' is a pointer; did you mean to use '->'?

✅ Right

struct N { int data; struct N *next; };
struct N b = { 20, NULL };
struct N *p = &b;
printf("%d\n", p->data);

p is a pointer to a node, not a node. Use -> to reach a member through a pointer; . is only for a struct variable itself.

❌ Wrong

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

struct Node { int data; struct Node *next; };

void push_front(struct Node *head, int v) {
    struct Node *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->data = v;
    n->next = head;
    head = n;
}

int main(void) {
    struct Node *head = NULL;
    push_front(head, 5);
    if (head != NULL) printf("first = %d\n", head->data);
    else printf("list is empty\n");
    return 0;
}

Compiles and runs, but prints: list is empty ⏎

✅ Right

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

struct Node { int data; struct Node *next; };

void push_front(struct Node **head, int v) {
    struct Node *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->data = v;
    n->next = *head;
    *head = n;
}

int main(void) {
    struct Node *head = NULL;
    push_front(&head, 5);
    if (head != NULL) printf("first = %d\n", head->data);
    else printf("list is empty\n");
    free(head);
    return 0;
}

C passes arguments by value, so the function changed only its own copy of head. main's head stayed NULL (and the node leaked). Pass &head and take a struct Node **.

❌ Wrong

struct N { int data; struct N *next; };
struct N c = { 30, NULL }, b = { 20, &c }, a = { 10, &b };
struct N *head = &a;
while (head != NULL) { printf("%d ", head->data); head = head->next; }
int count = 0;
for (struct N *p = head; p; p = p->next) count++;
printf("\nnodes: %d\n", count);

Compiles and runs, but prints: 10 20 30 ⏎ nodes: 0 ⏎

✅ Right

struct N { int data; struct N *next; };
struct N c = { 30, NULL }, b = { 20, &c }, a = { 10, &b };
struct N *head = &a;
for (struct N *p = head; p != NULL; p = p->next) printf("%d ", p->data);
int count = 0;
for (struct N *p = head; p; p = p->next) count++;
printf("\nnodes: %d\n", count);

Walking with head itself moves head to NULL, and the list is lost. Always walk with a separate pointer p and keep head pointing at the first node.

📌 Remember

  • A linked list is a chain of nodes; each node holds data and a pointer to the next node.
  • The head points to the first node; the last node's next is NULL.
  • Make nodes with malloc and pass &head when a function must change the head.
  • Inserting or deleting in the middle only changes pointers; nothing is shifted.
  • Walk with a separate pointer, and free every node (save next first) when you are done.

Finished the quiz and the challenge?

Questions students ask

What is the difference between an array and a linked list in C?

An array is one block of memory, so arr[i] is instant but inserting in the middle means shifting. A linked list is spread out and joined by pointers, so inserting is cheap but reaching the i-th item means walking from the head.

Why do we use a double pointer (struct Node **) in linked lists?

Because C copies arguments into functions. To change the caller's head pointer, the function needs the address of that pointer, which is a pointer to a pointer.

What is a doubly linked list?

Each node has two pointers: next and prev. You can walk both ways and delete a node without searching for the one before it. It costs one extra pointer per node.

Do linked lists cause memory leaks?

Only if you forget to free nodes. Every malloc needs one free. When you delete the whole list, save each node's next pointer before you free the node.