#include <stdio.h>
#include <stdlib.h>
#define MAX_POINT_NUM 10 //最大頂點數
/*
圖存儲方法:
1.鄰接矩陣(有向圖)
2.鄰接表
3.多重鄰接表
3.十字交叉鏈表(有向圖)
*/
//下面是無向圖鄰接表的實現的方法
//鄰接節點類型
typedef struct arcnode
{
int end_point_no;//結束的節點值
int weight;//記錄權重值
struct arcnode* next_arcnode;//指向下一個節點
}arcnode;
//定義記錄節點編號與指向第一個節點指針
typedef struct
{
int begin_point_no;
arcnode * ptr_first;
}vartex_node;
//定義無向圖
typedef struct
{
vartex_node array[MAX_POINT_NUM];
int vertex_num;
int arc_num;
}undigraph;
//根據頂點編號計算出在矩陣 的下標值
int get_locat_position(undigraph * graph,int v)
{
int i;
for(i=0;i<graph->vertex_num;i++)
{
if(graph->array[i].begin_point_no==v)
{
return i;
}
}
return -1;
}
//初始化有向圖
void init_undigraph(undigraph * graph)
{
//輸入圖頂點數和邊數
printf("please input vertex num and arc num:\n");
scanf("%d%d",&graph->vertex_num,&graph->arc_num);
//輸入頂點名稱,並記錄到vertex中
printf("please input vertex info:\n");
int i ;
for(i=0;i<graph->vertex_num;i++)
{
scanf("%d",&graph->array[i].begin_point_no);
graph->array[i].ptr_first=NULL;
}
//輸入邊(起始點 終止點 權重值)
for(i=0;i<graph->arc_num;i++)
{
int v1,v2,weight;
scanf("%d%d%d",&v1,&v2,&weight);
int r=get_locat_position(graph,v1);
int c=get_locat_position(graph,v2);
arcnode * ptr_new_node=(arcnode*)malloc(1*sizeof(arcnode));
ptr_new_node->end_point_no=c;
ptr_new_node->weight=weight;
ptr_new_node->next_arcnode=graph->array[r].ptr_first;
graph->array[r].ptr_first=ptr_new_node;
arcnode* ptr_new_node_two=(arcnode*)malloc(1*sizeof(arcnode));
ptr_new_node_two->end_point_no=r;
ptr_new_node_two->weight=weight;
ptr_new_node_two->next_arcnode=graph->array[c].ptr_first;
graph->array[c].ptr_first=ptr_new_node_two;
}
}
//輸出鄰接表(輸出無向圖)
void print_undigraph(undigraph * graph)
{
int i;
for(i=0;i<graph->vertex_num;i++)
{
if(graph->array[i].ptr_first!=NULL)
{
printf("begin point %d \n:",graph->array[i].begin_point_no);
arcnode * ptr_tmp=graph->array[i].ptr_first;
while(ptr_tmp!=NULL)
{
printf(" \t\tend point %d weight %d:\n",ptr_tmp->end_point_no,ptr_tmp->weight);
ptr_tmp=ptr_tmp->next_arcnode;
}
}
}
}
int main(int argc,const char* argv[])
{
undigraph graph;
init_undigraph(&graph);
print_undigraph(&graph);
return 0;
}
運行結果: