#include<iostream>
#include<malloc.h>
using namespace std;
#define VERTEX_MAX 20
typedef struct edgeNode{
int Vertex;//頂點(diǎn)序號(hào)
int weight;//權(quán)值
struct edgeNode *next;//指向有邊的下一個(gè)頂點(diǎn)
}EdgeNode;
typedef struct{
EdgeNode* AdjList[VERTEX_MAX];//指向每個(gè)頂點(diǎn)的指針
int VertexBum,EdgeNum;//圖的頂點(diǎn)的數(shù)量和邊的數(shù)量
int GraphType;//圖的類型:0:有向圖 1:無(wú)向圖
}ListGraph;
void CreatGraph(ListGraph *G);//生成圖的鄰接表
void OutList(ListGraph *G);//輸出鄰接表
void CreatGraph(ListGraph *G){
int i,weight;
int start,end;
EdgeNode *s;
for(int i=1;i<=G->VertexBum;i++)//清空?qǐng)D的頂點(diǎn)
G->AdjList[i]=NULL;
for(int i=1;i<=G->EdgeNum;i++){//輸入各邊的兩個(gè)頂點(diǎn)
getchar();
cout<<"第"<<i<<"條邊:";
cin>>start>>end>>weight; //輸入邊的起點(diǎn)個(gè)終點(diǎn)
s=(EdgeNode *)malloc(sizeof(EdgeNode));//申請(qǐng)一個(gè)保存頂點(diǎn)的內(nèi)存
s->next=G->AdjList[start]; //插入到鄰接表中
s->Vertex= end; //保存終點(diǎn)編號(hào)
s->weight=weight; //保存權(quán)值
G->AdjList[start]=s; //鄰接表對(duì)應(yīng)頂點(diǎn)指向該點(diǎn)
if(G->GraphType==0){ //若是無(wú)向圖,再插入到終點(diǎn)的邊鏈中
s=(EdgeNode *)malloc(sizeof(EdgeNode));
s->next = G->AdjList[end];
s->Vertex = start;
s->weight = weight;
G->AdjList[end] = s;
}
}
}
void OutList(ListGraph *G){
int i;
EdgeNode *s;
for(int i=1;i<=G->VertexBum;i++){
cout<<"頂點(diǎn)"<<i;
s=G->AdjList[i];
while(s){
cout<<"->"<<s->Vertex<<"("<<s->weight<<")";
s = s->next;
}
cout<<endl;
}
}
int main(){
ListGraph G;
cout<<"輸入生成圖的類型(0:無(wú)向圖 1:有向圖)";
cin>>G.GraphType;
cout<<"請(qǐng)輸入圖的頂點(diǎn)數(shù)量個(gè)邊數(shù)量:";
cin>>G.VertexBum>>G.EdgeNum;
cout<<"輸入構(gòu)造各邊的兩個(gè)頂點(diǎn)及權(quán)值(用空格分隔)"<<endl;
CreatGraph(&G);
cout<<"輸出圖的鄰接表";
OutList(&G);
getchar();
return 0;
}
實(shí)例輸入:
0
5 6
1 2 2
1 3 5
1 5 3
2 4 4
3 5 5
2 5 2
運(yùn)行結(jié)果截圖: