# 图的邻接表的创建、深度优先遍历和广度优先遍历

## 1.邻接表的定义

``````#define NUM		8
typedef int vex;

typedef struct __ArcNode
{
struct __ArcNode *nextarc;
}ArcNode;

typedef struct __VNode
{
vex data;
ArcNode *firstarc;
}VNode;``````

## 2.图邻接表的创建、销毁与显示

``````status CreateGraph(VNode *AdjList)
{
int i;
int c;
ArcNode **p;

for(i = 0; i < NUM; i++)//1 2 3 4 5
{
}

for(i = 0; i < NUM; i++)
{
scanf("%d", &c);
while(c != 0)
{
*p = (ArcNode *)malloc(sizeof(ArcNode));
p = &(*p)->nextarc;
scanf("%d", &c);
}
*p = NULL;
}
return TRUE;
}

{
int i;
ArcNode *p, *pt;
for(i = 0; i < NUM; i++)
{
while(p)
{
pt = p->nextarc;
free(p);
p = pt;
}
}
return TRUE;
}

{
int i;
ArcNode *p;

for(i = 0; i < NUM; i++)
{
while(p)
{
p = p->nextarc;
}
}
}``````

## 3.获得邻接点

``````ArcNode *FirstAdjVex(VNode *adj, vex v)
{
int i;
i = v - 1;
}

{
int i;
ArcNode *p;
i = v - 1;

while(p)
{
{
break;
}
else
{
p = p->nextarc;
}
}
if(p != NULL)
{
p = p->nextarc;
}
return p;
}``````

## 4.深度优先遍历

``````void visitNode(VNode *adj, vex n)
{
}

int vexflag[NUM];
{
ArcNode *p;
vex m;

vexflag[n - 1] = 1;

{
if(vexflag[m - 1] == 0)
{
}
}

return TRUE;
}

{
int i;
for(i = 0; i < NUM; i++)
{
vexflag[i] = 0;
}

for(i = 0; i < NUM; i++)
{
if(vexflag[i] == 0)
{
}
}

return TRUE;
}``````

## 5.广度优先遍历

``````status BFSTraverse(VNode *adj, void (*visit)(VNode *adj, vex n))
{
int i;
vex n;
vex m;
ArcNode *p;
queue q;

for(i = 0; i < NUM; i++)
{
vexflag[i] = 0;
}
initqueue(&q);

for(i = 0; i < NUM; i++)
{
if(vexflag[i] == 0)
{
vexflag[i] = 1;
enqueue(&q, i + 1);

while(!IsEmptyQueue(&q))
{
dequeue(&q, &n);
{
if(vexflag[m - 1] == 0)
{
vexflag[m - 1] = 1;
enqueue(&q, m);
}
}
}
}
}

destroyqueue(&q);
}``````

## 6.测试

``````int main()
{
ArcNode *p;

//	freopen("1.txt", "r", stdin);

printf("\n");