十字链表实现有向图
/*十字链表实现有向图*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode{
int ArcTail,ArcHead; /*分别表示弧尾,弧头*/
struct ArcNode * HeadLink, * TailLink; /*分别表示链头,链尾*/
}ArcNode;
typedef struct VexNode{
int data; /*顶点信息*/
ArcNode * firstin,* firstout; /*分别表示该顶点第一个入弧,出弧*/
}VexNode,VNode[MAX_VERTEX_NUM];
typedef struct OLGraph{
VNode HeadNode;
int vexnum,arcnum; /*分别表示顶点数,弧数*/
}OLGraph;
void Print_OLGraph(OLGraph * G)
{
int v;
ArcNode * p1,* p2;
printf("\n打印十字链表:\n");
for(v=0;v<G->vexnum;v++){
printf("%d \n",v);
if(G->HeadNode[v].firstout!=NULL){
printf(" V%d TailisSame: ",G->HeadNode[v].data);
p1=G->HeadNode[v].firstout;
while(p1){
printf(" <%d,%d>",p1->ArcTail,p1->ArcHead);
p1=p1->TailLink;
}
}
if(G->HeadNode[v].firstin!=NULL){
printf("\n V%d HeadisSame: ",G->HeadNode[v].data);
p2=G->HeadNode[v].firstin;
while(p2){
printf(" <%d,%d>",p2->ArcTail,p2->ArcHead);
p2=p2->HeadLink;
}
}
printf("\n");
}
}
int SerchSubscript(OLGraph * G,int v)
{
int k,n;
for(k=0;k<G->vexnum;k++){
if(G->HeadNode[k].data==v){
n=k;
break;
}
}
return n;
}
void InsertAdj(OLGraph * G,int i,int j)
{
ArcNode * a1,* a2,* a3;
a1=(ArcNode *)malloc(sizeof(ArcNode));
a1->ArcTail=i;a1->ArcHead=j;a1->HeadLink=NULL;a1->TailLink=NULL;
if(G->HeadNode[i].firstout!=NULL||G->HeadNode[j].firstin!=NULL){
if(G->HeadNode[i].firstout!=NULL){
a2=G->HeadNode[i].firstout;
while(a2->TailLink){
a2=a2->TailLink;
}
a2->TailLink=a1;
}
else{
G->HeadNode[i].firstout=a1;
}
if(G->HeadNode[j].firstin!=NULL){
a3=G->HeadNode[j].firstin;
while(a3->HeadLink){
a3=a3->HeadLink;
}
a3->HeadLink=a1;
}
else{
G->HeadNode[j].firstin=a1;
}
}
else{
G->HeadNode[i].firstout=a1;
G->HeadNode[j].firstin=a1;
}
}
void Init_OLGraph(OLGraph * G)
{
int v,k,v1,v2,i,j;
printf("输入(点,弧): ");
scanf("%d,%d",&G->vexnum,&G->arcnum);
for(v=0;v<G->vexnum;v++){
printf("输入点: ");
scanf("%d",&G->HeadNode[v].data);
G->HeadNode[v].firstin=NULL;
G->HeadNode[v].firstout=NULL;
}
for(k=0;k<G->arcnum;k++){
printf("输入<点,点>: ");
scanf("%d,%d",&v1,&v2);
i=SerchSubscript(G,v1);
j=SerchSubscript(G,v2);
InsertAdj(G,i,j);
}
Print_OLGraph(G);
}
int main(int argc,char **argv)
{
OLGraph G;
Init_OLGraph(&G);
return 0;
}