溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

用圖的鄰接表法創(chuàng)建圖的實現(xiàn)完整C代碼怎么寫

發(fā)布時間:2021-10-14 14:25:44 來源:億速云 閱讀:125 作者:柒染 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)用圖的鄰接表法創(chuàng)建圖的實現(xiàn)完整C代碼怎么寫,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

/* 無向圖的鄰接表法創(chuàng)建圖的C代碼實現(xiàn) */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MaxSize 20   //圖頂點的最大數(shù)量

typedef char VertexType;

//全局變量,記錄圖的結(jié)點的數(shù)量
int VertexNum;

//定義圖頂點
typedef struct GraphNode {
	VertexType ver;
	struct GraphNode *next;
}GraphNode;

//用鄰接表法創(chuàng)建圖
void CreateGraph( GraphNode **g )
{
	VertexType ch;						//用來接收頂點名稱
	int i = 0;
	GraphNode *p, *q;
	(*g) = (GraphNode *)malloc(sizeof(GraphNode)*MaxSize);//分配一個結(jié)構(gòu)體數(shù)組

	printf("請輸入圖的頂點:\n");		//存儲圖的頂點
	scanf("%c", &ch);
	while( '\n' != ch ) {
		(*g)[i].ver = ch;
		(*g)[i].next = NULL;
		i++;
		scanf("%c", &ch);
	}
	
	VertexNum = i;						//記錄頂點數(shù)
	
	for( i=0; i<VertexNum; i++ ) {		//存儲圖的邊信息
		q = (*g)+i;
		printf("請輸入頂點 %c 的鄰接頂點:\n", q->ver );
		scanf("%c", &ch);
		while( '\n' != ch ) {
			p = (GraphNode *)malloc(sizeof(GraphNode));
			p->ver = ch;
			q->next = p;
			q = p;
			q->next = NULL;
			scanf("%c", &ch);
		}
	}
}

//打印鄰接表法創(chuàng)建的圖
void PrintGraph( GraphNode *g )
{
	GraphNode *p;
	printf("圖的頂點為:\n");		//打印頂點
	for( int i=0; i<VertexNum; i++ )
		printf("%c ", g[i].ver);
	printf("\n");

	printf("圖的頂點以及其對應(yīng)的鄰接頂點為:\n");  //打印鄰接點
	for( i=0; i<VertexNum; i++ ) {
		printf("%c :", g[i].ver);
		p = g[i].next;
		while( NULL != p ) {
			printf("%c ", p->ver);
			p = p->next;
		}
		printf("\n");
	}
}

int main()
{
	GraphNode *g;

	CreateGraph( &g );

	PrintGraph( g );

	return 0;
}

測試的圖:

用圖的鄰接表法創(chuàng)建圖的實現(xiàn)完整C代碼怎么寫

測試結(jié)果

用圖的鄰接表法創(chuàng)建圖的實現(xiàn)完整C代碼怎么寫

關(guān)于用圖的鄰接表法創(chuàng)建圖的實現(xiàn)完整C代碼怎么寫就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI