C Linked List Program

A linked list stores data in nodes. Each node has a value and a pointer to the next node, so the nodes can be anywhere in memory. This program creates a list, prints it, deletes a value and frees all the memory.

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

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

struct Node *insertEnd(struct Node *head, int value) {
    struct Node *node = malloc(sizeof(struct Node));
    node->data = value;
    node->next = NULL;

    if (head == NULL) return node;

    struct Node *p = head;
    while (p->next != NULL) p = p->next;
    p->next = node;
    return head;
}

void display(struct Node *head) {
    for (struct Node *p = head; p != NULL; p = p->next) {
        printf("%d -> ", p->data);
    }
    printf("NULL\n");
}

struct Node *deleteValue(struct Node *head, int value) {
    struct Node *prev = NULL, *p = head;

    while (p != NULL && p->data != value) {
        prev = p;
        p = p->next;
    }
    if (p == NULL) return head;          // not found

    if (prev == NULL) head = p->next;    // first node
    else prev->next = p->next;
    free(p);
    return head;
}

void freeList(struct Node *head) {
    while (head != NULL) {
        struct Node *next = head->next;
        free(head);
        head = next;
    }
}

int main(void) {
    struct Node *head = NULL;

    head = insertEnd(head, 10);
    head = insertEnd(head, 20);
    head = insertEnd(head, 30);
    display(head);

    head = deleteValue(head, 20);
    display(head);

    freeList(head);
    return 0;
}

Output:

Output of the above program is

10 -> 20 -> 30 -> NULL
10 -> 30 -> NULL

How it works

  • insertEnd() creates a node with malloc() and adds it after the last node.
  • deleteValue() finds the node, links the previous node to the next one, and frees the deleted node.
  • freeList() frees every node, so there is no memory leak.
Note: The functions return the head, because the head can change (for example when the first node is deleted). Related: Structures, Dynamic Memory Allocation and Pointer to Structure.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.