C实现图的邻接链表存储

实现代码:

#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;
}

 

结果:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值