pi_coder/examples/c-linkedlist/linked_list.c

43 lines
935 B
C
Raw Normal View History

#include <stdlib.h>
#include <stdio.h>
#include "linked_list.h"
Node *node_new(int value) {
Node *n = malloc(sizeof(Node));
n->value = value;
n->next = NULL;
return n;
}
Node *list_prepend(Node *head, int value) {
Node *n = node_new(value);
n->next = head;
return n;
}
Node *list_append(Node *head, int value) {
Node *n = node_new(value);
if (!head) return n;
Node *cur = head;
while (cur->next) cur = cur->next;
cur->next = n;
return head;
}
void list_print(const Node *head) {
for (const Node *cur = head; cur; cur = cur->next)
printf("%d ", cur->value);
printf("\n");
}
/* BUG: Speicher wird nicht freigegeben — valgrind meldet Leaks. */
void list_free(Node *head) {
(void)head; /* TODO: implementieren */
}
int list_length(const Node *head) {
int len = 0;
for (const Node *cur = head; cur; cur = cur->next)
len++;
return len;
}