我是一個初級的編碼器,並且我正在編碼dfs bfs,它重複地顯示錯誤,我已經爲我至少使用了指針指向了一個節點數組,但是當我爲每個數組成員的元素賦值,其顯示錯誤。這是唯一的錯誤ACCORF =對我來說,親愛的幫助!在C++深度第一次搜索和breaf第一搜索實現
struct node
{
int dat;
int vstd;
struct node *nxt;
};
struct node **graph=(struct node**)malloc(5*sizeof(struct node*));
void initial()
{
for(int i=0;i<5;i++)
struct node *(graph[i])=(struct node*)malloc(sizeof(struct node));
}
struct node *head=NULL;
void visited(struct node *strt)
{
struct node *temp;
for(int i=0;i<5;i++)
{
temp=graph[i];
while(temp!=NULL)
{
if(temp->dat==strt->dat)
temp->vstd=1;
temp=temp->nxt;
}
}
}
struct node* find(struct node *gelem)
{
for(int i=0;i<5;i++)
{
if(graph[i]->dat==gelem->dat)
return(graph[i]);
}
return NULL;
}
void dfs(struct node *gelem)
{
struct node *temp;
visited(gelem);
cout<<gelem->dat<<endl;
temp=find(gelem);
while(temp!=NULL)
{
if(temp->vstd!=1)
{
dfs(temp);
}
temp=temp->nxt;
}
}
void dpthfrst()
{
struct node *temp;
for(int v=0;v<5;v++)
{
temp=graph[v];
while(temp!=NULL)
{
temp->vstd=0;
temp=temp->nxt;
}
}
for(int v=0;v<5;v++)
{
temp=graph[v];
while(temp!=NULL)
{
if(temp->vstd!=1)
dfs(temp);
temp=temp->nxt;
}
}
}
void bfs(struct node *grtemp)
{
struct node *head,*temp,*tmp2,*tmp3;
ins(head,grtemp);
do
{
temp=del(head);
visited(temp);
cout<<temp->dat<<endl;
tmp2=temp->nxt;
while(tmp2!=NULL)
{
tmp3=find(tmp2);
ins(head,tmp3);
}
}while(!isemp(head));
}
void brthfrst()
{
struct node *temp;
for(int v=0;v<5;v++)
{
temp=graph[v];
while(temp!=NULL)
{
temp->vstd=0;
temp=temp->nxt;
}
}
for(int v=0;v<5;v++)
{
temp=graph[v];
while(temp!=NULL)
{
if(temp->vstd!=1)
bfs(temp);
temp=temp->nxt;
}
}
}
void insrtnode()
{
struct node *temp;
struct node *nnode=(struct node*)malloc(sizeof(struct node));
struct node *tnode=(struct node*)malloc(sizeof(struct node));
int s,d,f1=0,f2=0;
cout<<"Insert the connection"<<endl;
cin>>s;
cin>>d;
nnode->dat=s;
nnode->nxt=NULL;
nnode->vstd=0;
tnode->dat=d;
tnode->nxt=NULL;
tnode->vstd=0;
for(int i=0;i<5;i++)
{
if(graph[i]->dat==s)
f1=1;
if(graph[i]->dat==d)
f2=1;
}
if(f1==0 && f2==0 && cnt<3)
{
for(int i=0;i<5;i++)
{
if(graph[i]==NULL)
{
graph[i]=nnode;
graph[i]->nxt=tnode;
graph[i++]=tnode;
cnt+=2;
break;
}
}
}
else if((f1==1 && f2==0 && cnt<4)||(f1==0 && f2 ==1 && cnt<4))
{
if(f1==1)
{
for(int i=0;i<5;i++)
{
if(graph[i]->dat==s)
{
temp=graph[i];
while(temp->nxt!=NULL)
temp=temp->nxt;
temp->nxt=tnode;
}
if(graph[i]==NULL)
{
graph[i]=tnode;
cnt++;
return;
}
}
}
if(f2==1)
{
for(int i=0;i<5;i++)
{
if(graph[i]==NULL)
{
graph[i]=nnode;
graph[i]->nxt=tnode;
cnt++;
return;
}
}
}
}
else
{
cout<<"Not a valid insertion";
return;
}
}
int main()
{
initial();
int ch;
char ans;
do
{
cout<<"1.INSERT\n 2.DFS \n 3.BFS\n";
cin>>ch;
switch(ch)
{
case 1: insrtnode();
break;
case 2:dpthfrst();
break;
case 3:brthfrst();
break;
default :cout<<"Invalid \n";
}
cout<<"Do you want to continue?(y/n)";
cin>>ans;
}
while(ans=='y'||ans=='Y');
return 0;
}
你得到什麼錯誤? –
可變大小的對象圖無法初始化 – user3505754