给定一个集合S = {x1,x2,x3,x4,x5,....},其大小为n(

 #include <stdio.h>
#include <stdbool.h>

typedef struct{
    int data;
    struct node* next;
}node;

void addEdge(node* graph[],int a,int b){
    node *ptr=(node *)malloc(sizeof(node));
    ptr->next=graph[a];
    ptr->data=b;
    graph[a]=ptr;
}

void buildGraph(node* graph[],int n){

    int i,j;
    for(i=2;i<=n;i++){
        for(j=1;j<=i/2;j++){
            if(i%j==0){
                if(j!=1) addEdge(graph,i/j,i);
                else addEdge(graph,j,i);
            }
        }
    }
}

void printGraph(node* graph[],int n){
    int i=0;
    node *ptr;
    for(i=0;i<=n;i++){
        ptr=graph[i];
        printf("Row-%d ",i);
        while(ptr!=NULL){
            printf("%d ",ptr->data);
            ptr=ptr->next;
        }
        printf("\n");
    }
}

void print(int array[],int n){
    int i;
    for(i=0;i<n;i++) printf("%d ",array[i]);
    printf("\n");
}

bool checkDuplicate(int array[],int n,int a){
    int i;
    for(i=0;i<n;i++) if(array[i]==a) return false;
    return true;
}
void formLattice(node* graph[],int lattice[],int k,int vertex,int level){
    //printf("Level-%d \n",level);
    if(level>k) return;
    if(level==k) {
        lattice[level-1]=vertex;
        print(lattice,k);
        return;
    }
    lattice[level-1]=vertex;
    node* ptr=graph[vertex];
    while(ptr!=NULL){
    //  if(checkDuplicate(lattice,level,ptr->data))
        formLattice(graph,lattice,k,ptr->data,level+1);
        ptr=ptr->next;
    }
}
void printLattice(node* graph[],int n,int k){
    int lattice[k],i;
    node* ptr;
    for(i=1;i<=n;i++){
        ptr=graph[i];
        while(ptr!=NULL){
            lattice[0]=i;
            formLattice(graph,lattice,k,ptr->data,2);
            ptr=ptr->next;
        }
    }
}
int main(void) {

    int n=10,k=4;
    node* graph[n+1];
    int i;
    for(i=0;i<=n;i++) graph[i]=NULL;
    buildGraph(graph,n);
//  printGraph(graph,n); // Comment to print out the Hasse Diagram
    printLattice(graph,n,k);
    return 0;
}


显示分段错误(核心已转储)
知道为什么会这样吗?
提前致谢

最佳答案

formLattice()的代码具有证据表明,仅对连接到lattice[level]lattice[level-1]那些顶点进行了探测。当然,并非每个晶格都具有总顺序(即{1,2,3,6}没有)。当顶点2存储到lattice[2]时,当前程序如何选择lattice[1]的顶点3?

换句话说,必须存在另一个循环,在lattice的当前循环周围,将0中所有已选择的顶点从level-1转换为ptr

09-12 09:29