Skip to content

Instantly share code, notes, and snippets.

@kgtkr
Created December 14, 2019 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgtkr/69e1a5743535228c3051bee35c0120db to your computer and use it in GitHub Desktop.
Save kgtkr/69e1a5743535228c3051bee35c0120db to your computer and use it in GitHub Desktop.
c linked list
#include <stdio.h>
#include <stdlib.h>
typedef struct _LinkedList {
void *head;
struct _LinkedList *tail;
} LinkedList;
LinkedList* list_tail(void) {
return NULL;
}
LinkedList* list_cons(void *head, LinkedList *tail) {
LinkedList* list = malloc(sizeof(LinkedList));
list -> head = head;
list -> tail = tail;
return list;
}
void list_free(LinkedList *list) {
if (list != NULL) {
free(list -> head);
list_free(list -> tail);
free(list);
}
}
int list_len(LinkedList *list) {
if (list == NULL) {
return 0;
} else {
return 1 + list_len(list -> tail);
}
}
void* list_get(LinkedList *list, int i) {
if (i == 0) {
return list -> head;
} else {
return list_get(list -> tail, i - 1);
}
}
void list_set(LinkedList *list, int i, void *x) {
if (i == 0) {
free(list -> head);
list -> head = x;
} else {
list_set(list -> tail, i - 1, x);
}
}
int* malloc_int(int x) {
int *p = malloc(sizeof(int));
*p = x;
return p;
}
void list_int_print(LinkedList *list) {
if (list == NULL) {
printf("\n");
} else {
printf("%d, ", *(int*)(list -> head));
list_int_print(list -> tail);
}
}
int main(int argc, char *args[])
{
LinkedList *list = list_cons(malloc_int(10), list_cons(malloc_int(5), list_cons(malloc_int(4), list_tail())));
printf("len: %d\n", list_len(list));
printf("list[2]: %d\n", *(int*)(list_get(list, 2)));
list_int_print(list);
list_set(list, 1, malloc_int(100));
list_int_print(list);
list_free(list);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment