Linked list
A singly linked list with malloc and free, written with compact pointer syntax.
+ <stdio.h>
+ <stdlib.h>
## A singly linked list: structs, pointers and malloc are plain C.
s Node
value: i32
next: *Node
f push(head: *Node, value: i32) *Node
n: *Node = malloc(sizeof(Node))
n->value = value
n->next = head
< n
f total(head: *Node) i32
sum := 0
for p: *Node = head; p; p = p->next
sum += p->value
< sum
f release(head: *Node)
while head
next: *Node = head->next
free(head)
head = next
f main()
list: *Node = NULL
for i := 1; i <= 5; i++
list = push(list, i * i)
for p: *Node = list; p; p = p->next
printf("%d ", p->value)
printf("\ntotal %d\n", total(list))
release(list)
< 0
#include <stdio.h>
#include <stdlib.h>
typedef struct Node Node;
struct Node {
int value;
Node *next;
};
Node *push(Node *head, int value) {
Node *n = malloc(sizeof(Node));
n->value = value;
n->next = head;
return n;
}
int total(Node *head) {
int sum = 0;
for (Node *p = head; p; p = p->next) {
sum += p->value;
}
return sum;
}
void release(Node *head) {
while (head) {
Node *next = head->next;
free(head);
head = next;
}
}
int main(void) {
Node *list = NULL;
for (int i = 1; i <= 5; i++) {
list = push(list, i * i);
}
for (Node *p = list; p; p = p->next) {
printf("%d ", p->value);
}
printf("\ntotal %d\n", total(list));
release(list);
return 0;
}
Output
25 16 9 4 1
total 55
What it shows
pointers, malloc, structs