-3
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.當我合併這兩個列表時,我得到正確的輸出,但在我的最後一個條件中,它給出了一個分段錯誤,當最後一個元素列表被合併。我怎樣才能消除這個錯誤?
大家給予更多的則7行的代碼應該先調試呀 – levu
,真的是無可救藥.. –
Zé[email protected]是的,它是在這裏,我只有在邊界條件如何克服problrem它 –