#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20
/*邊表的數據結構*/
typedef struct ArcBox{
int tailvex,headvex;//該弧的尾和頂點的位置
struct ArcBox *hlink,*tlink;//分別爲弧頭和弧尾相同的弧的鏈域
}ArcBox;
/*頂點結點的數據結構*/
typedef struct VexNode{
char data;
ArcBox *firstin,*firstout;//分別指向該頂點第一條入弧和出弧
}VexNode;
/*十字鏈表的數據結構*/
typedef struct{
VexNode xlist[MAX_VERTEX_NUM];//表頭向量
int vexnum,arcnum;//有向圖的當前結點數和邊數
}OLGraph;
/*查找頂點所在的位置*/
int locateVex(OLGraph G,char v)
{
int i=0;
for(i=0;i<G.vexnum;i++)
{
if(G.xlist[i].data==v)
return i;
}
return -1;
}
/*創建十字鏈表*/
void CreateOLG(OLGraph &G)
{
printf("請輸入當前圖的頂點總個數和總邊數:\n");
scanf("%d%d",&G.vexnum,&G.arcnum);
setbuf(stdin,NULL);
int i=0;
printf("請輸入頂點的數據:\n");
for(i=0;i<G.vexnum;i++)
{
scanf("%c",&G.xlist[i].data);
getchar();
G.xlist[i].firstin=NULL;
G.xlist[i].firstout=NULL;//初始化頂點
}
setbuf(stdin,NULL);
printf("請輸頂點之間邊的關係:\n");
int k=0;
int j=0;
char v1;
char v2;
for(k=0;k<G.arcnum;k++){
scanf("%c,%c",&v1,&v2);
setbuf(stdin,NULL);
i=locateVex(G,v1);
j=locateVex(G,v2);
ArcBox *p1=(ArcBox *)malloc(sizeof(ArcBox)); //針對輸出的firstout域
p1->headvex=j;
p1->tailvex=i;
p1->hlink=NULL;
p1->tlink=NULL;//將邊關係存儲在*p1指針裏面
p1->tlink=G.xlist[i].firstout;
G.xlist[i].firstout=p1;
p1->hlink=G.xlist[j].firstin;//針對輸入的firstin域
G.xlist[j].firstin=p1;
}
}
int main()
{
OLGraph G;
CreateOLG(G);
printf("鄰接表打印:\n");
int i=0;
ArcBox *p=(ArcBox *)malloc(sizeof(ArcBox));
for(i=0;i<G.vexnum;i++){
printf("%c",G.xlist[i].data);
p->tlink=G.xlist[i].firstout;
while(p->tlink!=NULL){
printf("->%c",G.xlist[p->tlink->headvex].data);
p->tlink=p->tlink->tlink;
}
printf("\n");
}
printf("打印逆鄰接表:\n");
for(i=0;i<G.vexnum;i++){
printf("%c",G.xlist[i].data);
p->hlink=G.xlist[i].firstin;
while(p->hlink!=NULL){
printf("->%c",G.xlist[p->hlink->tailvex].data);
p->hlink=p->hlink->hlink;
}
printf("\n");
}
return 0;
}
測試數據:
有錯的話,歡迎留言。。。。