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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!