附加列表 - 分段错误

cra*_*liv 1 c linked-list segmentation-fault

我试图将一个列表附加到另一个列表中.如果我传递两个列表的指针指针并只显示它们,那么代码工作正常.但是如果我使用代码到达第一个列表的NULL指针,然后将它等同于第二个列表中的第一个,那么它会给出一个分段错误.请让我知道错误是什么.代码如下:

#include<stdio.h>
#include<stdlib.h>
struct node 
{
    int data;
    struct node* next;
}*Head,*New;
void display(struct node **p)
{
    struct node *curptr;
    curptr=*p;
    if(curptr==NULL)
        printf("list is empty");
    else
    {
        while(curptr)
        {
            printf("->%d",curptr->data);
            curptr=curptr->next;
        }
    }
}
void combine(struct node **a,struct node **b)
{
    //display(&(*a));
    struct node *aptr;
    aptr=*a;
    while(aptr)
        aptr=aptr->next;
    aptr->next=*b;
    *b=NULL;
    display(&(*a));

    //display(&(*a));
    //display(&(*b));   

}
void main()
{
    Head=NULL;
    New=NULL;
    int choice;
    while(1)
    {
          case 9:
        {
            printf("Combining two lists");
            combine(&Head,&New);
            break;
        }
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 5

问题出在这里:

while(aptr)
    aptr=aptr->next;
aptr->next=*b
Run Code Online (Sandbox Code Playgroud)

当你跳出的while循环aptrNULL当您尝试做下一个aptr->next你得到的SEGV.

当你到达最后一个节点(aptr->next将是NULL)而不是aptr变成时,要解决这个突破NULL.

这些东西:

// if fist list does not exist.
if(*a == NULL) {
        *a = *b;
        return;
}

struct node *aptr;
aptr=*a;

// loop till you reach the last node of fist list.
while(aptr->next)
        aptr=aptr->next;

// append.
aptr->next=*b;
*b=NULL; 
Run Code Online (Sandbox Code Playgroud)