以下是我写的链表的有序合并,可是却出现图片的问题,有的输出正确,有时输出错误请大神帮忙找找问题所在
以下是我写的链表的有序合并,有的输出正确,有时输出错误请大神帮忙找找问题所在#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct DATA)
struct DATA
{
long num;
struct DATA *next;
};
struct DATA *create(int n)
{
struct DATA *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct DATA *)malloc(LEN);
scanf("%ld",&p1->num);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
struct DATA *merge(struct DATA *head, struct DATA *head2)
{
struct DATA *p;
p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next=head2;
return head;
}
struct DATA *insert(struct DATA *head, struct DATA *d)
{
struct DATA *p0,*p1,*p2;
p0=head;p1=d;
if(head==NULL) head=p1;
else
{
while(p1->num>p0->num&&p0->next!=NULL)
{
p2=p0;p0=p0->next;
}
if( p1->num < p0->num )
{ if( head==p0 ) head=p1;
else p2->next=p1;
p1->next=p0; }
else { p0->next=p1;}
}
return head;
}
struct DATA *sort(struct DATA *head)
{
struct DATA *p1,*p2;
p1=head;p2=head;
p1=p1->next;
p2->next=NULL;
p2=p1;
while(p1->next!=NULL)
{
p1=p1->next;
p2->next=NULL;
head=insert(head,p2);
p2=p1;
}
head=insert(head,p2);
return head;
}
void print(struct DATA *head)
{
struct DATA *p;
p=head;
while(p!=NULL)
{
printf("%ld",p->num);
p=p->next;
printf("\n");
}
}
main()
{
struct DATA *head, *head2;
int n;
long del_num;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
head2=create(n);
head = merge(head, head2);
head = sort(head);
print(head);
}