#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define NULL 0
#define MAX_VERTEX_NUM 20 // 最大頂點數
typedef struct ArcNode
{
int adjvex; //該邊所指的頂點的位置
struct ArcNode *nextarc; //指向下一條邊的指針
int weight; //邊的權
}ArcNode; //表的結點
typedef struct VNode
{
char data; //頂點信息(如數據等)
ArcNode *firstarc; //指向第一條依附該頂點的邊的弧指針
}VNode, AdjList[MAX_VERTEX_NUM]; //頭結點
typedef struct ALGraph
{
AdjList vertices;
int vexnum, arcnum; //圖的當前頂點數和弧數
}ALGraph;
//返回頂點v在頂點向量中的位置
int LocateVex(ALGraph &G, char v)
{
int i;
for(i = 0; v != G.vertices[i].data && i < G.vexnum; i++)
;
if(i >= G.vexnum)
return -1;
return i;
}
//增加節點
void add_vex(ALGraph &G)
{
printf ("輸入無向圖頂點數: \n");
cin>>G.vexnum;
//getchar(); //喫回車
printf ("輸入頂點信息:\n");
for(int i = 0; i < G.vexnum; i++)
{
cin>>G.vertices[i].data; //構造頂點向量
G.vertices[i].firstarc = NULL;
//getchar();
}
}
//增加邊
void add_arc(ALGraph &G)
{
ArcNode *s, *t;
printf ("輸入無向圖邊數: \n");
cin>>G.arcnum;
char v1, v2;
printf ("輸入邊信息:\n");
for(int k = 0; k < G.arcnum; k++)
{
cin>>v1>>v2;
int i = LocateVex(G, v1);
int j = LocateVex(G, v2); //確定v1 , v2在G中的位置
s = (ArcNode*) malloc (sizeof(ArcNode));
t = (ArcNode*) malloc (sizeof(ArcNode));
s->adjvex = j; //該邊所指向的頂點的位置爲j
s->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc =s;
t->adjvex = i; //該邊所指向的頂點的位置爲j
t->nextarc = G.vertices[j].firstarc;
G.vertices[j].firstarc =t;
}
}
//構造鄰接鏈表
void CreateUDN(ALGraph &G)
{
add_vex(G); //增加節點
add_arc(G); //增加邊
}
void PrintAdjList(ALGraph &G)
{
int i;
ArcNode *p;
printf ("編號 頂點 鄰點編號\n");
for(i = 0; i < G.vexnum; i++)
{
cout<<" "<<i<<" "<<G.vertices[i].data<<" ";
for(p = G.vertices[i].firstarc; p; p = p->nextarc)
cout<<p->adjvex<<" ";
cout<<endl;
}
}
int main()
{
ALGraph G;
CreateUDN(G);
PrintAdjList(G);
return 0;
}
圖的鄰接表表示
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.