实现代码:
#include <stdio.h>
#include <malloc.h>
typedef enum { OK = 1,ERROR = 0 }Status;
#define elem char
typedef struct _node {
elem value;
int weight;
_node *next;
}Node,*link;
typedef struct _graphlinklist {
int v;
int e;
link list;//node **list为 node*数组
}GraphLinkList,*GLL;
Node* newnode(elem e) {
Node *newnode = (Node*)malloc(sizeof(Node));
newnode->value = e;
newnode->next = NULL;
return newnode;
}
GLL initGraph(char vs[]) {
int n = strlen(vs);
GLL g = (GLL)malloc(sizeof(GraphLinkList));
g->v = n;
g->e = 0;
g->list = (link)malloc(sizeof(Node)*n);
for (int i = 0; i < n; i++) {
g->list[i].value = vs[i];
g->list[i].next = NULL;
}
return g;
}
int index(elem v,link list,int n) {
for (int i = 0; i < n; i++) if (list[i].value == v) return i;
return -1;
}
Status addEdge(elem start, elem end, GLL g) {
link list = g->list;
int from = index(start, list ,g->v), to = index(end, list,g->v);
if (-1 == start||-1 == end || start == end) return ERROR; //不能自反
Node* addnode = newnode(end);
addnode->next = list[from].next;
list[from].next = addnode;
g->e++;
return OK;
}
Status addWeightEdge(elem start, elem end, GLL g) {
link list = g->list;
int from = index(start, list, g->v), to = index(end, list, g->v);
if (-1 == start || -1 == end || start == end) return ERROR; //不能自反
Node* addnode = newnode(end);
addnode->next = list[from].next;
list[from].next = addnode;
return OK;
}
void printGraph(GLL g) {
int n = g->v;
for (int i = 0; i < n; i++) {
Node* temp = &(g->list[i]);
while (temp) {
printf("%c-->", temp->value);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
char vs[9] = { 'A','B','C','D','E','F','G','H','\0' };//char vs[] = "abcd";
GLL g = initGraph(vs);
addEdge('A', 'B', g); addEdge('A', 'C', g); addEdge('A', 'D', g); addEdge('A', 'E', g); addEdge('A', 'F', g);
addEdge('B', 'B', g); addEdge('B', 'C', g); addEdge('B', 'D', g); addEdge('B', 'E', g); addEdge('B', 'F', g);
printGraph(g);
return 0;
}
结果: