You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
1.8 KiB
89 lines
1.8 KiB
6 months ago
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
#define TABLE_SIZE 100
|
||
|
|
||
|
typedef struct Node {
|
||
|
int key;
|
||
|
char value[256];
|
||
|
struct Node* next;
|
||
|
} Node;
|
||
|
|
||
|
typedef struct Edge {
|
||
|
Node* from;
|
||
|
Node* to;
|
||
|
double cost;
|
||
|
struct Edge* next;
|
||
|
} Edge;
|
||
|
|
||
|
typedef struct Graph {
|
||
|
Node* nodes[TABLE_SIZE];
|
||
|
Edge* edges[TABLE_SIZE];
|
||
|
} Graph;
|
||
|
|
||
|
unsigned int hash(int key) {
|
||
|
return key % TABLE_SIZE;
|
||
|
}
|
||
|
|
||
|
void insertNode(Graph* g, int key, const char* value) {
|
||
|
unsigned int index = hash(key);
|
||
|
Node* new_node = (Node*) malloc(sizeof(Node));
|
||
|
if (new_node) {
|
||
|
new_node->key = key;
|
||
|
strcpy(new_node->value, value);
|
||
|
new_node->next = g->nodes[index];
|
||
|
g->nodes[index] = new_node;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
Node* findNode(Graph* g, int key) {
|
||
|
unsigned int index = hash(key);
|
||
|
Node* node = g->nodes[index];
|
||
|
while (node) {
|
||
|
if (node->key == key)
|
||
|
return node;
|
||
|
node = node->next;
|
||
|
}
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
void insertEdge(Graph* g, int fromKey, int toKey, double cost) {
|
||
|
Node* fromNode = findNode(g, fromKey);
|
||
|
Node* toNode = findNode(g, toKey);
|
||
|
if (fromNode && toNode) {
|
||
|
unsigned int index = hash(fromKey);
|
||
|
Edge* new_edge = (Edge*) malloc(sizeof(Edge));
|
||
|
if (new_edge) {
|
||
|
new_edge->from = fromNode;
|
||
|
new_edge->to = toNode;
|
||
|
new_edge->cost = cost;
|
||
|
new_edge->next = g->edges[index];
|
||
|
g->edges[index] = new_edge;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void initGraph(Graph* g) {
|
||
|
for (int i = 0; i < TABLE_SIZE; i++) {
|
||
|
g->nodes[i] = NULL;
|
||
|
g->edges[i] = NULL;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
int main() {
|
||
|
Graph g;
|
||
|
initGraph(&g);
|
||
|
|
||
|
insertNode(&g, 1, "Node 1");
|
||
|
insertNode(&g, 2, "Node 2");
|
||
|
insertEdge(&g, 1, 2, 0.5);
|
||
|
|
||
|
Node* n = findNode(&g, 1);
|
||
|
if (n) {
|
||
|
printf("Found node: %s\n", n->value);
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|