#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define MAX_VRTEX_NUM 20
struct EdgeNode{
int adjvex;
struct EdgeNode *next;
};
typedef struct EdgeNode **adjlist;
void Initialization(adjlist &GL,int n);
void Create(adjlist &GL,int n,int m);
void DFS(adjlist GL,int *visited,int i,int n);
void Check(int n,int &i,int &j);
void Initialization(adjlist &GL,int n)
{
GL=(EdgeNode **)malloc(sizeof(2*n));
for(int i=1;i<=n;i++)
{
GL[i]=NULL;
}
}
void Create(adjlist &GL,int n,int m)
{
int i,j,k,e;
printf("Enter the total number of edges:");
scanf("%d",&e);
if(m==0)
{
for(k=1;k<=e;k++)
{
printf("Input the No.%d edge's startpoint and endpoint:\n",k);
scanf("%d %d",&i,&j);
char temp=getchar();
Check(n,i,j);
struct EdgeNode *p;
p=(struct EdgeNode *)malloc(sizeof(struct EdgeNode));
p->adjvex=j;
p->next=GL[i];
GL[i]=p;
p=(struct EdgeNode *)malloc(sizeof(struct EdgeNode));
p->adjvex=i;
p->next=GL[j];
GL[j]=p;
}
printf("\n==============\n");
printf("Adjacency-list representetion:\n");
for(i=1;i<=n;i++)
{
struct EdgeNode *p=GL[i];
printf("%d |V%d",i-1,i);
for(p=GL[i];p!=NULL;p=p->next)
{
printf("|-|->|%d",p->adjvex);
}
printf("|^|");
printf("\n");
}
}
else
if(m==1)
{
for(k=1;k<=e;k++)
{
printf("Input the No.%d edge's startpoint and endpoint:\n",k);
scanf("%d %d",&i,&j);
Check(n,i,j);
struct EdgeNode *p;
p=(struct EdgeNode *)malloc(sizeof(struct EdgeNode));
p->adjvex=j;
p->next=GL[i];
GL[i]=p;
}
printf("Adjacency-list representetion:\n");
for(i=1;i<=n;i++)
{
struct EdgeNode *p=GL[i];
printf("%d |V%d",i-1,i);
for(p=GL[i];p!=NULL;p=p->next)
{
printf("|-|->|%d",p->adjvex);
}
printf("|^|");
printf("\n");
}
}
}
void DFS(adjlist GL,int *visited,int i,int n)
{
printf("%d ",i);
visited[i]=1;
struct EdgeNode *p=GL[i];
while(p!=NULL)
{
int j=p->adjvex;
if(!visited[j])
DFS(GL,visited,j,n);
p=p->next;
}
}
void Check(int n,int &i,int &j)
{
while(true)
{
if(i<=0||i>n||j<=0||j>n)
printf("Entry error, please re-enter!\n");
else
return;
scanf("%d %d",&i,&j);
}
}
void main()
{
int i,n,m;
printf("==============\n");
printf("Input graph vertices:");
scanf("%d",&n);
printf("Undirected graph:input 0 OR Digraph:input 1:");
scanf("%d",&m);
int visited[MAX_VRTEX_NUM];
adjlist gl;
Initialization(gl,n);
Create(gl,n,m);
printf("==============\n");
printf("Depth-first search:\n");
for(i=1;i<=n;i++)
visited[i]=0;
DFS(gl,visited,1,n);
}
The main purpose of the program is to output the sequence of a graph with the Depth-first search. When I debugged it on visual c++ 2008, there is no error. But it can't run properly. It stops running after I input the first edge's startpoint and endpoint. I can't find the solution.:confused: What's more, I am a beginner. I just started learning the Graph. Could you help me, please? Thanks. :)