此代码是数据结构的原始模板,可以刚接触或考研时借鉴下,不适于刷题
#include<stdio.h>
#include<malloc.h>
#include<stack>
#define MAX_VERTEX_NUM 20
using namespace std;
int visited[100];
typedef struct arcnode
{
int adjvex;
struct arcnode *nextarc;
int info;
}*arcnod,arcnode1;
typedef struct vertexnode
{
int data;
arcnode1 *firstarc;
}*vertexnod,vertex;
typedef struct
{
vertex ver[MAX_VERTEX_NUM];
int vexnum,arcnum;
}*adjlist,adjlist1;
int find(adjlist &g,int x)
{
int x1;
for(int i=0;i<g->vexnum;i++)
{
if(g->ver[i].data==x)
{
x1=i;
break;
}
}
return x1;
}
void create(adjlist &g)
{
int i,k=1,x1,x2;
arcnod s1;
printf("请输入顶点数和边数: ");
scanf("%d%d",&g->vexnum,&g->arcnum);
printf("请输入顶点信息: ");
for(i=0;i<g->vexnum;i++)
{
scanf("%d",&g->ver[i].data);
g->ver[i].firstarc=NULL;
}
for(i=0;i<g->arcnum;i++)
{
adjlist g1,g2;
g1=g;
g2=g;
printf("请输入第%d边的起点,终点,表示顶点起点到终点: ",k++);
scanf("%d%d",&x1,&x2);
int t1=x1,t2=x2;
x1=find(g1,x1);
x2=find(g2,x2);
s1=(arcnod)malloc(sizeof(arcnode1));
s1->adjvex=x2;
s1->nextarc=g->ver[x1].firstarc;
g->ver[x1].firstarc=s1;
}
}
int firstadjvertex(adjlist &g,int k)
{
if(g->ver[k].firstarc!=NULL)
return g->ver[k].firstarc->adjvex;
else
return -1;
}
int nextadjvertex(arcnod &p,int k)
{
if(p->nextarc!=NULL)
return p->nextarc->adjvex;
else
return -1;
}
void depthfirstsearch(adjlist &g,int v0)
{
int k,w;
stack<int>dsta;
stack<int>dstb;
arcnod p;
dstb.push(v0);
while(dstb.empty()!=1)//输出栈中的顶点
{
k=dstb.top();
dstb.pop();
if(visited[k]!=1)
{
printf("%d ",g->ver[k].data);
visited[k]=1;
w=firstadjvertex(g,k);
p=g->ver[k].firstarc;
while(w!=-1)
{
if(visited[w]!=1)
dsta.push(w);
w=nextadjvertex(p,w);
p=p->nextarc;
}
while(dsta.empty()!=1)
{
dstb.push(dsta.top());
dsta.pop();
}
}
}
}
void traversegraph(adjlist &g)
{
for(int i=0;i<g->vexnum;i++)
visited[i]=0;
for(i=0;i<g->vexnum;i++)
{
if(visited[i]==0)
{
depthfirstsearch(g,i);
}
}
}
int main()
{
adjlist g;
g=(adjlist)malloc(sizeof(adjlist1));
create(g);
traversegraph(g);
printf("\n");
return 0;
}