one-file-projects/adjliste.c

112 lines
2.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <assert.h>
#define GET_CLOCK() ((float)clock() / CLOCKS_PER_SEC)
typedef uint32_t Node;
typedef struct node_list {
Node node;
struct node_list* next;
} *NodeList, NodeElement;
typedef struct {
NodeList* const node_lists;
uint32_t const node_count;
} AdjList;
AdjList al_Create(uint32_t node_count) {
NodeList* node_lists = malloc(sizeof(NodeList)*node_count);
for(Node i = 0; i < node_count; i++) {
node_lists[i] = NULL;
}
return (AdjList){ node_lists, node_count };
}
void al_AddEdge(AdjList al, Node nodefrom, Node nodeto) {
if(al.node_lists[nodefrom] == NULL) {
NodeElement* element = al.node_lists[nodefrom] = malloc(sizeof( NodeElement ));
element->node = nodeto;
element->next = NULL;
} else {
NodeElement* iter = al.node_lists[nodefrom];
while(iter->next != NULL) {
if(iter->node == nodeto) return;
iter = iter->next;
}
NodeElement* new = malloc(sizeof(NodeElement));
new->node = nodeto;
new->next = NULL;
iter->next = new;
}
}
void al_RemoveEdge(AdjList al, Node nodefrom, Node nodeto) {
if(al.node_lists[nodefrom] == NULL)
return;
else if(al.node_lists[nodefrom]->node == nodeto) {
NodeElement* element = al.node_lists[nodefrom];
al.node_lists[nodefrom] = element->next;
free(element);
} else if(al.node_lists[nodefrom]->next != NULL){
NodeElement* iter = al.node_lists[nodefrom];
while(iter->next->node != nodeto) {
if(iter->next == NULL) return;
iter = iter->next;
}
NodeElement* deleteme = iter->next;
iter->next = deleteme->next;
free(deleteme);
}
}
int al_TestEdge(AdjList al, Node nodefrom, Node nodeto) {
NodeElement* iter = al.node_lists[nodefrom];
while(iter != NULL) {
if(iter->node == nodeto) return 1;
iter = iter->next;
}
return 0;
}
void al_Free(AdjList al) {
for(Node i = 0; i < al.node_count; i++) {
NodeElement* iter = al.node_lists[i];
NodeElement* tmp;
while(iter != NULL) {
tmp = iter;
iter = iter->next;
free(tmp);
}
}
free(al.node_lists);
}
int main( int argc, char *argv[] ) {
AdjList b = al_Create(1000);
float start, end;
start = GET_CLOCK();
for(Node i = 0; i < 1000; i++) {
al_AddEdge(b,i,i);
for(Node j = i+1; j < i+49 && j < 1000; j++) {
al_AddEdge(b,i,j);
al_AddEdge(b,j,i);
}
}
end = GET_CLOCK();
printf("%.3f msecs\n", (end-start) * 1e3);
al_Free(b);
return 0;
}