LearnFrenzy
Sign in Take a free test

Typedef · typedef Programs · Question 8

Linked list with a Node typedef: append, length and free Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Using typedef struct node Node;, build a list by appending values, print it with its length, and free it.

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

typedef struct node Node;          /* declared first, so the struct can use Node */
struct node {
    int value;
    Node *next;
};

void append(Node **head, int v) {
    Node *n = malloc(sizeof *n);
    if (n == NULL)
        return;
    n->value = v;
    n->next = NULL;
    while (*head != NULL)
        head = &(*head)->next;
    *head = n;
}

int length(const Node *p) {
    int n = 0;
    for (; p != NULL; p = p->next)
        n++;
    return n;
}

int main(void) {
    Node *list = NULL;
    for (int v = 10; v <= 30; v += 10)
        append(&list, v);
    for (const Node *p = list; p != NULL; p = p->next)
        printf("%d -> ", p->value);
    printf("NULL (length %d)\n", length(list));
    while (list != NULL) {
        Node *next = list->next;
        free(list);
        list = next;
    }
    return 0;
}

Output Verified by compiling and running

10 -> 20 -> 30 -> NULL (length 3)

Declaring typedef struct node Node; before the struct definition lets the struct's own members use the short name – the other common way to write self-referencing typedefs.

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.

Search LearnFrenzy

Esc

Quick links