#include "stdafx.h"
#include"iostream.h"
const int n=8;
const int e=15;
typedef int elemtype ;
bool visited[n+1];
class link
{public:
elemtype data;
link *next;
};
class graph
{public:
link a[n+1];
void creatlink()
{int i,j,k;
link *s;
for(i=1;i<=n;i++)
{a[i].data=i;
a[i].next=NULL;
}
for(k=1;k<=e;k++)
{cout<<"请输入一条边";
cin>>i>>j;
cout<<endl;
s=new link;
s->data=j;
s->next=a[i].next;
a[j].next=s;
}
}
void dfs1(int i)
{link *p;
cout<<a[i].data<<" ";
visited[i]=true;
p=a[i].next;
while(p!=NULL)
{if(!visited[p->data])
dfs1(p->data);
p=p->next;
}
}
void bfs1(int i)
{int q[n+1];
int f,r;
link *p;
f=r=0;
cout<<a[i].data<<" ";
visited[i]=true;
r++;q[r]=i;
while(f<r)
{f++;i=q[r];
p=a[i].next;
while(p!=NULL)
{if(!visited[p->data])
{cout<<a[p->data].data<<" ";
visited[p->data]=true;
r++;q[r]=p->data;
}
p=p->next;
}
}
}
};
void main()
{link *p;int yn=1;
graph g;
g.creatlink();
while(yn){
for(int i=1;i<=n;i++)
{p=g.a[i].next;
cout<<g.a[i].data<<"->";
while(p->next!=NULL)
{cout<<p->data<<"->";
p=p->next;
}
cout<<p->data<<endl;
}
for(i=1;i<=n;i++)
visited[i]=false;
cout<<"输入深度优先搜索开始访问的顶点";
cin>>i;
cout<<endl;
cout<<"从"<<i<<"出发的深度优先搜索遍历序列为"<<endl;
g.dfs1(i);
cout<<endl;
for(i=1;i<=n;i++)
visited[i]=false;
cout<<"请输入广度优先搜索开始访问的顶点";
cin>>i;
cout<<endl;
cout<<"从"<<i<<"出发的广度优先搜索遍历序列为"<<endl;
g.bfs1(i);
cout<<endl;
cout<<"继续遍历吗(1/0)?";
cin>>yn;
}}
图为:
1 2 3
5 4
6 7 8