#include <stdio.h>
#include <stdlib.h>
struct yuansu
{
int data;
struct yuansu *next;
};
struct yuansu *creat(void)
{
struct yuansu *head,*p1,*p2;
head=p1=(struct yuansu*)malloc(sizeof(struct yuansu));
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
printf("请输入链表元素(输入-1时结束):\n\t");
scanf("%d",&p2->data);
while(p2->data!=-1)
{
p1->next=p2;
p1=p2;
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
scanf("%d",&p2->data);
}
p1->next=NULL;
free(p2);
return head;
}
int bianli(struct yuansu *head)
{
int count=0;
while(head->next!=NULL)
{
count++;
head=head->next;
}
return count;
}
void print(struct yuansu *head)
{
head=head->next;
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
}
int main()
{
struct yuansu *head1,*head2,*head,*p1,*p2;
int m,n;
printf("请输入单链表A:\n");
head1=creat();
m=bianli(head1);
printf("请输入单链表B:\n");
head2=creat();
n=bianli(head2);
if(m>n)
{
head=p1=(struct yuansu*)malloc(sizeof(struct yuansu));
while(head2->next!=NULL)
{
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
head2=head2->next;
p2->data=head2->data;
p1->next=p2;
p1=p2;
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
head1=head1->next;
p2->data=head1->data;
p1->next=p2;
p1=p2;
}
while(head1->next!=NULL)
{
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
head1=head1->next;
p2->data=head1->data;
p1->next=p2;
p1=p2;
}
}
else
{
head=p1=(struct yuansu*)malloc(sizeof(struct yuansu));
while(head1->next!=NULL)
{
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
head1=head1->next;
p2->data=head1->data;
p1->next=p2;
p1=p2;
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
head2=head2->next;
p2->data=head2->data;
p1->next=p2;
p1=p2;
}
while(head2->next!=NULL)
{
p2=(struct yuansu*)malloc(sizeof(struct yuansu));
p2->data=head2->data;
p1->next=p2;
p1=p2;
}
p1->next=NULL;
free(p2);
free(head1);
free(head2);
}
printf("线性单链表C的元素为:\n\t");
print(head);
system("pause");
return 0;
}
当输入少量数据时会出现死循环,当输入大量数据时会显示正确的结果但还会出现运行停止的对话框。
求大神解决