Skip to content

Instantly share code, notes, and snippets.

@apua
Last active October 26, 2018 18:50
Show Gist options
  • Save apua/738353406736440be6d13757c800c837 to your computer and use it in GitHub Desktop.
Save apua/738353406736440be6d13757c800c837 to your computer and use it in GitHub Desktop.
Learn creating linked list in Rust style
// ref: https://doc.rust-lang.org/rust-by-example/custom_types/enum/testcase_linked_list.html
#include <stdio.h>
#include <stdlib.h>
enum NodeType { Cell, Nil };
typedef struct LinkedList LinkedList;
typedef struct NodeCell {
int car;
LinkedList * cdr;
} NodeCell;
typedef struct NodeNil {} NodeNil;
struct LinkedList {
enum NodeType type;
union {
NodeCell cell;
NodeNil nil;
};
};
NodeNil nil;
LinkedList * new() {
LinkedList * seq = malloc(sizeof(LinkedList));
seq->type = Nil;
seq->nil = nil;
return seq;
}
LinkedList * prepend(LinkedList * self, int element) {
NodeCell * cell = malloc(sizeof(NodeCell));
cell->car = element;
cell->cdr = self;
LinkedList * seq = malloc(sizeof(LinkedList));
seq->type = Cell;
seq->cell = *cell;
return seq;
}
int len(LinkedList * self) {
switch (self->type) {
case Cell:
return len(self->cell.cdr) + 1;
case Nil:
return 0;
}
}
char * stringify(LinkedList * self) {
char * buff = malloc(100 * sizeof(char));
switch (self->type) {
case Cell:
snprintf(buff, 100, "%i, %s", self->cell.car, stringify(self->cell.cdr));
return buff;
case Nil:
return "Nil";
}
}
int main() {
LinkedList * seq = new();
for (int i = 0; i < 10; i++)
seq = prepend(seq, i);
printf("%i\n", len(seq));
// 10
printf("%s\n", stringify(seq));
// 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, Nil
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment