LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 4

Linked list in C: insert at end, delete a value, print Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Implement a singly linked list with append, delete-by-value and print, and free all nodes at the end.

Solution
main.c
#include <stdio.h>
#include <stdlib.h>

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

void append(struct node **head, int v) {        /* ** so the head itself can change */
    struct node *n = malloc(sizeof *n);
    if (n == NULL)
        return;
    n->value = v;
    n->next = NULL;
    while (*head != NULL)
        head = &(*head)->next;
    *head = n;
}

void remove_value(struct node **head, int v) {
    for (; *head != NULL; head = &(*head)->next) {
        if ((*head)->value == v) {
            struct node *dead = *head;
            *head = dead->next;                   /* unlink, works for the first node too */
            free(dead);
            return;
        }
    }
}

void print(const struct node *p) {
    for (; p != NULL; p = p->next)
        printf("%d -> ", p->value);
    printf("NULL\n");
}

int main(void) {
    struct node *list = NULL;
    for (int v = 10; v <= 40; v += 10)
        append(&list, v);
    print(list);
    remove_value(&list, 10);
    remove_value(&list, 30);
    print(list);
    while (list != NULL) {
        struct node *next = list->next;
        free(list);
        list = next;
    }
    return 0;
}

Output Verified by compiling and running

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

Walking with a pointer to the link (struct node **) lets one piece of code unlink the first node and any later node – no special case for the head. Every malloc() is matched by a free().

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular