结构的随机图
问题描述:
我想实现一个随机图的代码,其中所有的顶点都相互连接。应该随机选择边缘。我写了这段代码:结构的随机图
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define VOL 100
struct node{
int info;
struct node *next;
};
struct node *read_list(void){
struct node *p, *first=NULL;
int i,V;
for(i=0;i<V;i++){
p=malloc(sizeof(struct node));
p->next=first;
p->info=rand()%V;
first=p;
}
return(first);
}
void print_list(struct node *p){
while(p!=NULL){
printf("%d-> ", p->info);
p=p->next;
}
printf("NULL\n");
return;
}
int read_graph(struct node *G[]){
int i, V;
printf("Select a number of vertices:\n");
scanf("%d", &V);
for(i=0;i<V;i++){
printf("Adjacency list of vertex %d:\n", i);
G[i]=read_list();
}
return(V);
}
void print_graph(struct node *G[], int V){
int i;
printf("Adjacency lists of the graph:\n");
for(i=0;i<V;i++){
printf("Adjacency vertices to %d: ",i);
print_list(G[i]);
}
return;
}
int adj(int i, int j, struct node *G[]){
int r;
struct node *p;
p=G[i];
while (p!=NULL && p->info !=j)
p=p->next;
if(p==NULL)
r=1;
else
r=0;
return (r);
}
int main(){
srand(time(NULL));
struct node *G[VOL], *L;
int V;
V=read_graph(G);
print_graph(G, V);
L=read_list();
return 0;
}
但是,它不起作用,我不知道为什么。 Xcode告诉我'构建成功',但代码不打印任何东西(目前只有'选择多个顶点'):没有邻接列表,没有边缘。请你检查它并告诉我错误在哪里?
答
In下面for
声明,变量V
未初始化。
...
struct node *read_list(void) {
struct node *p, *first = NULL;
int i, V; // <<<<<<<<<<<<<<<<<<< V not initialized
for (i = 0; i<V; i++) {
//^ trouble here
...
“不工作”是不是一个错误的描述,什么不起作用?它编译?它连接?它是否给了错误的输出?你期望什么?你的调试工作是什么? – Lundin
Xcode告诉我'构建成功',但代码不打印任何东西(目前只有'选择多个顶点'):没有邻接列表,没有边... –
@math。世界。请编辑您的问题,并精确描述您遇到的问题。不要在评论中提供相关信息。 –