#include
#include
struct node{
int vertex;
struct node *next;
};
struct headnode{
int vert;
struct node *link;
};
struct headnode *adjlist(int d[], int n){
struct headnode head[100] ;
struct node *p ;
int i,v1;
for(i=0;i
head[i].vert=d[i];
head[i].link=null;
printf("input linked list of\n");
scanf("%d",&v1);
while(v1>=0){
p=(struct node *) malloc(sizeof(struct node));
p->vertex=v1;
p->next=head[i].link ;
head[i].link=p;
scanf("%d",&v1);
}
}
return(head);
}
void dfs(struct headnode head[1000], int k,int *visit){
int i;
struct node *p;
if(visit[k]!=0) return;
printf(" v%d",k+1);
visit[k]=1;
p=head[k].link;
while (p!=null){
if (visit[p->vertex]==0)
dfs(head,p->vertex,visit);
p=p->next;
}
return;
}
void wfs(struct headnode *head,int n){
int visit[1000],q[1000];
int f,r,i,k,u,m;
struct node *p;
for(k=0;k
visit[k]=0;
for(m=0;m
if(visit[m]==0){
f=0;r=0;
q[r]=m;
r=r+1;
visit[m]=1;
while (f!=r){
u=q[f];
f=f+1;
printf(" v%d",u+1);
p=(head+u)->link;
while (p!=null){
if (visit[p->vertex]==0){
q[r]=p->vertex;
r=r+1;
visit[p->vertex]=1;
}
p=p->next;
}
}
}
}
}
int main(){
int t,n,i,visit[100];
int d[100];
struct headnode *head ;
printf("input the sum of nodes:\n");
scanf("%d",&n);
printf("input the value of each node:\n");
for(i=0;i
scanf("%d",&d[i]);
head=adjlist(d,n);
printf("1 depth travel\n");
printf("2 width travel\n");
printf("please input the way of travelling\n");
scanf("%d",&t);
switch(t){
case 1:
for(i=0;i
visit[i]=0;
for(i=0;i
dfs(head,i,visit);
printf("\n");
break;
case 2:
wfs(head,n);
printf("\n");
break;
default:
printf("the error!\n");
}
return 0;
}