首先我们先创建一个邻接表,先定义邻接表一些结构体。
我们要定义一个结构体来存放顶点的值,再定义结构体来存放所连接的顶点的值。
#define MaxVertexNum 100
typedef int VertexType;
typedef struct node //定义结构体来存放所连接的顶点的值。
{
int adjvex;
struct node *next;
}EdgeNode;
typedef struct //定义一个结构体来存放顶点的值
{
VertexType vertex;
EdgeNode *firstedge;
}VertexNode;
typedef VertexNode AdjList[MaxVertexNum]; //先定义100个顶点
typedef struct //定义一个结构存顶点和边
{
AdjList adjlist;
int n,e;
}ALGraph;
我们以上面的图为例子,来创建一个邻接表:
void create(ALGraph *G)
{
int i,j,k,w,v;
EdgeNode *s;
printf("读入顶点和边数");
scanf("%d %d",&G->n,&G->e);
for(i=0;in;i++)
{
printf("建立顶点表");
fflush(stdin);
scanf("%d",&G->adjlist[i].vertex);
G->adjlist[i].firstedge=NULL;
}
printf("建立边表\n");
for(k=0;ke;k++)
{
printf("读入(vi-vj)的顶点对序号");
scanf("%d %d",&i,&j);
i--;j--; //数组从0号开始存储
s=(EdgeNode*)malloc(sizeof(EdgeNode));
s->adjvex=j;
s->next=G->adjlist[i].firstedge;
G->adjlist[i].firstedge=s;
s=(EdgeNode*)malloc(sizeof(EdgeNode));
s->adjvex=i;
s->next=G->adjlist[j].firstedge;
G->adjlist[j].firstedge=s;
}
}
完成后我们在定义一个队列,以更快的方式来实现对邻接表的遍历。
typedef int Boolean;
Boolean visit[MaxVertexNum]; //作为标记使用,被访问的元素为1,否则为0.
typedef struct QNode //队列的节点
{
int data;
struct QNode *next;
}QNode,*Queueptr;
typedef struct //头指针和尾指针
{
Queueptr front ,rear;
}LinkQueue;
队列的操作:
int initQueue(LinkQueue *q) //初始化队列
{
q->front=q->rear=(Queueptr)malloc(sizeof(QNode));
if(!q->front)
{
return ERROR;
}
q->front->next=NULL;
return OK;
}
int EnQueue(LinkQueue *q,int e) //进队列
{
Queueptr s=(Queueptr)malloc(sizeof(QNode));
if(!s)
return ERROR;
s->data=e;
s->next=NULL;
q->rear->next=s;
q->rear=s;
return OK;
}
int DeQueue(LinkQueue *q,int *e) //出队列
{
Queueptr p;
if(q->front=q->rear)
{
return ERROR;
}
p=q->front->next;
*e=p->data;
q->front->next=p->next;
if(q->rear==p)
{
q->rear=q->front;
}
free(p);
return OK;
}
int QueueEmpty(LinkQueue q) //判断队列是否为空
{
if(q.front==q.rear)
{
return 1;
}
return 0;
}
广义优先遍历代码
void BFSTraverse(ALGraph *G)
{
int i;
EdgeNode *p;
LinkQueue Q;
for(i=0;in;i++)
visit[i]=FALSE;
initQueue(&Q);
for(i=0;in;i++)
{
if(!visit[i])
{
visit[i]=TRUE;
printf("%d ",G->adjlist[i].vertex);
EnQueue(&Q,i);
while(!QueueEmpty(Q))
{
DeQueue(&Q,&i);
p=G->adjlist[i].firstedge; //第i个元素的所连接的顶点
while(p)
{
if(!visit[p->adjvex])
{
visit[p->adjvex]=TRUE;
printf("%d ",G->adjlist[p->adjvex].vertex);
EnQueue(&Q,p->adjvex);
}
p=p->next;
}
}
}
}
printf("\n");
}
主函数:
#include
#include
#define MaxVertexNum 100
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1
void main()
{
ALGraph *G=(ALGraph *)malloc(sizeof(ALGraph));
EdgeNode *p;
create(G);
int i;
printf("邻接表的广义优先遍历是:\n");
BFSTraverse(G);
printf("其邻接表为('->'表示两个之间有连接):\n");
for(i=0;in;i++)
{
p=G->adjlist[i].firstedge;
printf("%d->",G->adjlist[i].vertex);
while(p!=NULL)
{
printf("%d->",G->adjlist[p->adjvex].vertex);
p=p->next;
}
printf("\n");
}
}