【发布时间】:2019-05-10 08:19:21
【问题描述】:
我创建了一个程序,它应该读取图中的顶点数,但我在使用链接列表创建顶点之间的链接时遇到了问题。我让它创建顶点并在一些节点之间创建链接,但由于某种原因,当我尝试输入某个顶点作为链接时它崩溃了。
例如 如果我将顶点数设为 4 并输入输入为 1 2 3 4 然后接下来是要链接的顶点我输入 1 以及要链接的顶点为 -1 2 3 我输入3后就崩溃了,为什么? 当我输入 2 作为顶点时,我可以与任何顶点链接。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct BFS_node
{
int data,vis;
struct BFS_node *linknodes;
};
typedef struct BFS_node node;
node *head,*N=NULL;
int num;
void create_node(node **Node)
{
if(*Node==NULL)
{
*Node=(node*)malloc(sizeof(node));
head=*Node;
}
else
*Node=*Node+1;
printf("%d enter the value \n",*Node);
scanf("%d",&(*Node)->data);
(*Node)->linknodes=(node *)malloc(num*sizeof(node));
printf(" %d \n",(*Node)->linknodes);
}
node * search_node(int num,node *head2)
{
while(head2)
{
if(head2->data==num)
return head2;
head2++;
}
}
void linking()
{
node *Dnode,**Lnode;
int num,i=0;
char Snum[10];
printf("enter the number you want to link ");
scanf("%d",&num);
Dnode=search_node(num,head);
printf("%d",Dnode);
while(getchar() != '\n' && getchar()!=EOF);
Lnode=Dnode->linknodes;
printf("enter the linked numbers");
while(fgets(Snum,sizeof(Snum),stdin))
{
if(sscanf(Snum,"%d",&num)!=1)
break;
*Lnode=search_node(num,head);
printf("%d %d",Lnode,*Lnode);
Lnode++;
}
}
BFStraversal()
{
int num,i=0;
node *queue[10],*link;
printf("enter the starting number");
scanf("%d",&num);
queue[i]=search_node(num,head);
link=queue[i]->linknodes;
printf("%d",link->data);
queue[i]->vis=1;
while(queue[i]!=NULL)
{
int j=1;
link=queue[i]->linknodes;
printf("%d",queue[i]->linknodes->data);
while(link->data !=NULL)
{
if(link->vis!=1)
{
queue[i+j]=link;
link->vis=1;
j++;
}
link++;
}
printf("%d",queue[i]->data);
i++;
}
}
int main()
{
printf("enter the number of vertices \n ");
scanf("%d",&num);
for(int i=0;i<num;i++)
create_node(&N);
for(int i=0;i<num;i++)
linking();
BFStraversal();
return 0;
}
【问题讨论】:
-
复习
while(getchar() != '\n' && getchar()!=EOF);为什么每个循环读2次? -
@chux 我用它从前一个 scanf 函数中清除缓冲区,以便在使用 fgets 进行链接输入时不会引起问题
-
我看到了问题。*Lnode=search_node(num,head);改变了3s节点数据的值
-
while(getchar() != '\n' && getchar()!=EOF);每个循环读取 2 个字符。int ch; while((ch = getchar()) != '\n' && ch != EOF);更有意义。
标签: c linked-list breadth-first-search