合并两种链表的排序

时间:2011-06-28 10:30:26

标签: c linked-list segmentation-fault

  

可能重复:
  merge two linked list into a single list

typedef struct node
{
int info;
struct node *NEXT;
}*NODE;


NODE insert_front(int item, NODE first)
{
NODE temp;
temp = ( struct node *) malloc( sizeof (struct node*));
temp -> info = item;
temp -> NEXT = first;
return temp;
}

void display(NODE first)
{
NODE temp;
if(first == NULL)
{
    printf("list is empty \n");
    return;
}
printf("contents of linked list \n");
temp = first;
while (temp!= NULL )
{
    printf("%d->",temp -> info);
    temp = temp->NEXT;
}
printf("\n");
}


NODE merger_list(NODE first1, NODE first2, NODE merger)
{
NODE merger_temp;
if(first1==NULL)
{
 printf("list1 is empty");
 exit(1);
}

if(first2==NULL)
{
    printf("list2 is empty");
    exit(1);
}
while(first1!=NULL)
{

merger_temp = ( struct node *) malloc( sizeof (struct node*));
if(first1->info > first2->info)
{
 merger_temp->info = first1->info;
 first1 = first1->NEXT;
}
else
{
 merger_temp->info = first2->info;
 first2 = first2->NEXT;
}

}

}
main()
{
NODE first1, first2, merger;
first1 = NULL;
first2 = NULL;
merger = NULL;
int choice, item;
while(1)
{
    printf("\n 1:Insert list1 \n 2: Insert list2 \n 3: display1 \n 4: display2 \n 5:merger_list \n
    printf("enter choice:\n");
    scanf ("%d",&choice);
    switch(choice)
    {
        case 1:
            printf("enter list1\n");
            scanf("%d",&item);
            first1 = insert_front(item,first1);
            break;

        case 2:
            printf("enter list2\n");
            scanf("%d",&item);
            first2 = insert_front(item,first2);
            break;
        case 3:
            display(first1);
            break;
        case 4:
            display(first2);
            break;

        case 5:
            merger_list(first1, first2, merger);
            break;
        case 6:
              display(merger);
            break;
        case 7:
            exit(0);

        default :
            printf("invalid data entered\n");
    }

}
}

此代码适用于合并两个链表。我有两个链表,list1有1 3 5 7而list2有2 4 6 8.当我合并这两个列表时,我得到了正确的输出,但在我的最后一个条件中,它给出了一个合并列表的最后一个元素时的分段错误。如何删除此错误?

1 个答案:

答案 0 :(得分:0)

在merger_list函数中,只要first1不为null,就会执行while循环。

但是,你也在推进前2名单。我怀疑这是你的问题。

尝试:

while((first1!=NULL) && (first2!=NULL))