Last active
December 30, 2015 10:29
-
-
Save Xjs/7816624 to your computer and use it in GitHub Desktop.
A typical linked list, possibly somewhat crudely implemented.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef union _data | |
{ | |
int i; | |
double d; | |
void *ptr; | |
} data_t; | |
typedef enum _data_type {INTEGER, DOUBLE, STRING, POINTER} data_type_t; | |
typedef struct _list | |
{ | |
union _data data; | |
enum _data_type type; | |
struct _list *next; | |
} list_t; | |
list_t *new_list(data_t data, data_type_t type) | |
{ | |
list_t *result = malloc(sizeof(list_t)); | |
if (result == NULL) | |
{ | |
printf("FAIL"); | |
return NULL; | |
} | |
result->data = data; | |
result->type = type; | |
result->next = NULL; | |
return result; | |
} | |
void append_to_list(list_t *head, list_t *new_node) | |
{ | |
list_t *current = head; | |
if (head == NULL) // what are you trying to append at? | |
return; | |
while (current->next != NULL) | |
current = current->next; | |
current->next = new_node; | |
return head; | |
} | |
void print_list(list_t *head) | |
{ | |
list_t *current = head; | |
int i = 0; | |
while (current != NULL) | |
{ | |
char format[] = "%5d %x\n"; | |
const int position = 5; | |
switch (current->type) | |
{ | |
case INTEGER: | |
format[position] = 'd'; | |
break; | |
case DOUBLE: | |
format[position] = 'f'; | |
break; | |
case STRING: | |
format[position] = 's'; | |
break; | |
default: | |
format[position] = 'p'; | |
} | |
printf(format, i++, current->data); | |
current = current->next; | |
} | |
} | |
void delete_list(list_t *head) | |
{ | |
list_t *current = head; | |
while (current != NULL) | |
{ | |
list_t *next = current->next; | |
free(current); | |
current = next; | |
} | |
} | |
int main (void) | |
{ | |
list_t *list; | |
data_t nine, five; | |
nine.i = 9; | |
five.i = 5; | |
list = new_list(five, INTEGER); | |
append_to_list(list, new_list(nine, INTEGER)); | |
append_to_list(list, new_list(five, INTEGER)); | |
append_to_list(list, new_list(nine, INTEGER)); | |
append_to_list(list, new_list(five, INTEGER)); | |
append_to_list(list, new_list(nine, INTEGER)); | |
append_to_list(list, new_list(five, INTEGER)); | |
append_to_list(list, new_list(nine, INTEGER)); | |
append_to_list(list, new_list(five, INTEGER)); | |
append_to_list(list, new_list(nine, INTEGER)); | |
append_to_list(list, new_list(five, INTEGER)); | |
append_to_list(list, new_list(nine, INTEGER)); | |
print_list(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment