C语言数据结构代码——有向图

Head.H

#define VEXNUMMAX 10

typedef enum
{
	DG = 0,
	DN,
	UDG,
	UDN
}EnumGraphKind;

typedef struct _ArcNode
{
	int vex_index;
	struct _ArcNode *nextarc;
}ArcNode,*arcnode;

typedef struct _VexNode
{
	char name;              // 顶点名字
	arcnode first_arc;      // 指向第一条依附该顶点的弧
}VexNode,*vexnode;

typedef struct _Graph
{
	int vexnum;             // 图的顶点的数目
	int arcnum;             // 图的边的数目
	VexNode vex[VEXNUMMAX];
}Graph,*graph;

graph InitGraph(char vex[], int vexlen, char arc[][2], int arclen);
int GetPos(graph G, char ch);
void PrintGraph(graph G);

 

 

Function.C

graph InitGraph(char vex[], int vexlen, char arc[][2], int arclen)
{
	graph G = (graph)malloc(sizeof(Graph));
	G->vexnum = vexlen;
	G->arcnum = arclen;

	//vex
	for (int i = 0; i < G->vexnum; i++)
	{
		G->vex[i].name = vex[i];
		G->vex[i].first_arc = NULL;
	}

	//arc
	char startnode_name, endnode_name;
	int startnode_pos, endnode_pos;

	for (int i = 0; i < G->arcnum; i++)
	{

		startnode_name = arc[i][0];
		endnode_name = arc[i][1];
		startnode_pos = GetPos(G, startnode_name);
		endnode_pos = GetPos(G, endnode_name);

		arcnode node = (arcnode)malloc(sizeof(ArcNode));
		node->vex_index = endnode_pos;
		node->nextarc = NULL;

		if (G->vex[startnode_pos].first_arc == NULL)
		{
			G->vex[startnode_pos].first_arc = node;
		}
		else
		{
			arcnode tempnode = G->vex[startnode_pos].first_arc;
			while (tempnode->nextarc != NULL)
			{
				tempnode = tempnode->nextarc;
			}
			tempnode->nextarc = node;
		}
	}

	return G;
}


int GetPos(graph G, char ch)
{
	for (int i = 0; i < G->vexnum; i++)
	{
		if (G->vex[i].name == ch)
		{
			return i;
		}
	}

	return -1;
}


void PrintGraph(graph G)
{
	for (int i = 0; i < G->vexnum; i++)
	{
		arcnode tempnode = G->vex[i].first_arc;
		printf("%c: ", G->vex[i].name);
		while (tempnode)
		{
			printf("(%d ,%c) ", tempnode->vex_index, G->vex[tempnode->vex_index].name);
			tempnode = tempnode->nextarc;
		}
		printf("\n");
	}
}

 

 

Main.C

void main(void)
{
	char vexs[] = { 'A','B', 'C', 'D','E' };
	char arcs[][2] = { {'A','B'} ,{'A','C'} , {'A','D'}, {'B','C'}, {'B','D'}, {'C','D'},{'D','E'} };

	int vexlen = sizeof(vexs) / sizeof(char);
	int arclen = sizeof(arcs) / (2 * sizeof(char));

	graph G = InitGraph(vexs, vexlen, arcs, arclen);
	PrintGraph(G);

	printf("\n");
	system("pause");
}

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值