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().
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!