链接列表prgrm停止工作错误

时间:2017-10-25 15:25:56

标签: c linked-list crash

我正在用C

编写一个链表程序

问题在于创建功能。 Create()在第一次运行时完美运行。然后,当我退出菜单并再次调用create函数时,程序崩溃并显示消息" linkedlist已停止工作"提示:linkedlist是我的prgrm的名称。

void create()
{
    do
   {
       printf("Enter the num:");
       head=(NODE *) malloc(sizeof(NODE));
       scanf("%d",&head->num);
       head->next=NULL;
       if(start==NULL)
           start=ptr=head;
       else
       {
           ptr->next=head;
           ptr=head;
       }
       printf("Do you want to enter more elements:(1/0)");
       scanf("%d",&ch);
   }
   while(ch==1);
}

1 个答案:

答案 0 :(得分:0)

我从你的代码中观察到你使用ptr作为指向链表的最后一个节点的指针,如create()函数的以下行所示: -

if (start==NULL)
    start = ptr = head;
else
{
    ptr->next=head;
    ptr=head;
}

在显示功能中,您再次初始化

ptr = start;

然后遍历到循环的末尾,其中ptr变为null,如下所示: -

while(ptr!=NULL)
{
    printf("%d->",ptr->num);
    ptr=ptr->next;
}

(类似于delast()和delany()函数,您正在执行以下操作: -

free(ptr);

这将再次导致ptr = null,从而导致分段错误。 )

因此,当您第一次创建列表时,代码工作正常,因为ptr的值被保留,但是,一旦显示列表,或删除任何元素,然后再返回创建列表(菜单选项1 ),ptr的值变为null,所以,

ptr->next = head;

导致细分错误

所以,一个可能的解决方案是在create()函数中使用一个新的指针,例如* end而不是* ptr,并且永远不要使end = null;如下图所示: -

void create()
{
 do{
    printf("Enter the num:");
    head=(NODE *) malloc(sizeof(NODE));
    scanf("%d",&head->num);
    head->next=NULL;
    if(start==NULL)
        start=end=head;
    else
    {
        end->next=head;
        end=head;
    }
    printf("Do you want to enter more elements:(1/0)");
    scanf("%d",&ch);
}
 while(ch==1);
}

或者,在创建列表时,您可以遍历到列表的末尾以添加新元素,而不是直接使用结束指针(因此,无需保存额外的结束指针)。

void create()
{
 do{
    printf("Enter the num:");
    head=(NODE *) malloc(sizeof(NODE));
    scanf("%d",&head->num);
    head->next=NULL;
    if(start == NULL)
        start = head;
    else
    {
        ptr = start;
        while (ptr->next != NULL){
            ptr = ptr->next;
        }
        ptr->next = head;
    }        
    printf("Do you want to enter more elements:(1/0)");
    scanf("%d",&ch);
}
 while(ch==1);
}