天天看點

兩個有序連結清單序列的合并(c語言程式設計題)題目答案注意

兩個有序連結清單序列的合并

  • 題目
  • 答案
  • 注意

題目

兩個有序連結清單序列的合并(c語言程式設計題)題目答案注意

答案

#include<stdio.h>
#include<malloc.h>
struct Array{
	int data;
	struct Array *next;
};
int main()
{
	struct Array *head,*head1,*pa,*pb,*head2,*p,*temp;
	head1=(struct Array *)malloc(sizeof(struct Array));
	head1->next=NULL;
	p=head1;
	int t;
	while(1)
	{
		scanf("%d",&t);
		if(t==-1) break;
		else
		{
			temp=(struct Array *)malloc(sizeof(struct Array));
			temp->data=t;
			temp->next=NULL;
			p->next=temp;
			p=p->next;
		}
	}
	head2=(struct Array *)malloc(sizeof(struct Array));
	head2->next=NULL;
	p=head2;
	while(1)
	{
		scanf("%d",&t);
		if(t==-1) break;
		else
		{
			temp=(struct Array *)malloc(sizeof(struct Array));
			temp->data=t;
			temp->next=NULL;
			p->next=temp;
			p=p->next;
		}
	}
	
	head=(struct Array *)malloc(sizeof(struct Array));
	head->next=NULL;
	p=head;
	pa=head1->next;
	pb=head2->next;
	while(pa&&pb)
	{
		if(pa->data<pb->data)
		{
			p->next=pa;
			p=p->next;
			pa=pa->next;
		}
		else
		{
			p->next=pb;
			p=p->next;
			pb=pb->next;
		}
	}
	p->next=pa?pa:pb;
	head1->next=NULL;
	head2->next=NULL;
	
	int flag=0;
	if(head->next==NULL)
	{
		printf("NULL");
		return 0;
	}
	while(head->next)
	{
		if(flag==0)
		{
			printf("%d",head->next->data);
			flag=1; 
		}
		else printf(" %d",head->next->data);
		head=head->next;
	}
} 
           

注意

如果malloc報錯,就在開頭加上這一句

繼續閱讀