使用C的无向图邻接列表实现

时间:2017-06-21 02:45:51

标签: graph linked-list

代码:

#include <stdio.h>
#include <stdlib.h>

#define N 5

typedef struct list
{
    int data;
    struct list * next;//self referenced structure
}slist;

void displayList(slist * start)
{
    slist * temp;
    if(start==NULL)
    {
        printf("Empty Linked List");
        return;
    }

    for(temp=start;temp!=NULL;temp=temp->next)
        printf("%d ",temp->data);

    return;
}

void insertLast(slist * * start,slist * node)
{
    slist * temp;
    if(start==NULL){
        (* start)=node;
        return;
    }
    temp=(* start);

    while((temp->next)!= NULL)
        temp=temp->next;

    temp->next=node;
    return;
}

int main()
{
    int i,j;
    //slist * node;
    char Ans;

    /*printf("Write the number of vertices\n");
    scanf("%d",&N);*/
    slist * start[N];
    for(i=0;i<N;i++)
        start[i]=NULL;

    for(i=0;i<N;i++)
    {
        for(j=i+1;j<N;j++)
        {
            printf("Is there a connection between V[%d] and V[%d]\n",(i+1),(j+1));
            scanf(" %c",&Ans);

            if(Ans=='y'||Ans=='Y')
            {
                slist * node1=(slist *)malloc(sizeof(slist));
                node1->data=(j+1); node1->next=NULL;
                insertLast(&start[i],node1);enter code here

                slist * node2=(slist *)malloc(sizeof(slist));
                node2->data=(i+1); node2->next=NULL;
                insertLast(&start[j],node2);
            }
        }
    }

    for(i=0;i<N;i++)
    {
        displayList(start[i]);
        printf("\n");
    }

    return 0;
}

上面的代码显示了写while((temp->next)!=NULL)的行的分段错误,而在创建链表时,相同的insertLast工作得很好。代码中的错误是什么?

1 个答案:

答案 0 :(得分:0)

当您检查start是否为NULL时,您的程序崩溃了。但这并不能保证*start也不是NULL。在这种情况下,temp获取NULL并且while循环temp->next实际上尝试访问NULL指针的next元素,这就是崩溃的原因。

更改此行 -

if(start==NULL)

if(*start==NULL)
insertLast()中的

将修复崩溃。

我还建议使用gdb之类的调试器来调试此类问题。