#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Arcnode {
int adjvex;
Arcnode* next;
};
struct Vertexnode {
char vertex;
Arcnode* first;
};
const int MAX_VERTEX = 10;
Vertexnode adjlist[MAX_VERTEX];
void Creategraph(char a[],int n,int e)
{
int vernum = n;
int arcnum = e;
for (int i = 0; i < vernum; i++)
{
adjlist[i].vertex = a[i];
adjlist[i].first = NULL;
}
for (int i = 0; i < arcnum; i++)
{
int vi, vj;
printf("边的起点和终点序号为:");
scanf_s("%d,%d", &vi, &vj);
Arcnode* s = (Arcnode*)malloc(sizeof(Arcnode));
s->adjvex = vj;
s->next = NULL;
//if ((adjlist[vi].first==NULL)||vj < (adjlist[vi].first->adjvex))
//{
s->next = adjlist[vi].first;
adjlist[vi].first = s;
//}
/*else
{
Arcnode* p = adjlist[vi].first;
Arcnode* b=NULL;
while(p->adjvex<vj)
{
b = p;
p = p->next;
}
s->next = p;
b->next = s;
}
*/
}
}
int vist[MAX_VERTEX] = { 0 };
void DFStraverse(int v) {
vist[v] = 1;
printf("%c", adjlist[v].vertex);
Arcnode* p = adjlist[v].first;
while (p != NULL)
{
if (vist[p->adjvex] == 0)
{
DFStraverse(p->adjvex);
p = p->next;
}
}
}
int visit[MAX_VERTEX] = { 0 };
void DFStraverse1(int v)
{
int stack[MAX_VERTEX];
int top = -1,w,x;
Arcnode* p = NULL;
printf("%c", adjlist[v].vertex);
visit[v] = 1;
top++;
stack[top] = v;
while (top > -1)
{
x = stack[top];
p = adjlist[x].first;
while(p != NULL)
{
w = p->adjvex;
if (visit[w] != 1)
{
printf("%c", adjlist[w].vertex);
visit[w] = 1;
top++;
stack[top] = w;
break;
}
p = p->next;
}
if (p == NULL)
top--;
}
}
int main()
{
char verlist[] = "ABCDEF";
Creategraph(verlist, 6, 6);
printf("深度搜索递归结果为\n");
DFStraverse1(0);
printf("\n");
printf("深度搜索非递归结果为\n");
DFStraverse(0);
}
运行截图如下: