6合并有序链表

#include<stdio.h>
#include<stdlib.h>
#define SIZE sizeof(struct linklist)
struct linklist {
	int data;
	struct linlist* next;
};
int main(void)
{
	struct linklist* head1,*head2,*head3,*r,*p,*q;
	int n,i,j,k,sum=0,l1,l2,l3;
	///////////////////////////////////////////////////////////////
	//第一个链表
	head1 = (struct linklist*)malloc(SIZE);
	p = head1;
	scanf_s("%d", &l1);
	getchar();
	sum += l1;
	n = l1;
	while (n--)
	{
		q = (struct linkist*)malloc(SIZE);
		if (q == NULL)
			return 0;
		scanf_s("%d",&q->data);
		getchar();
		p->next = q;
		p = q;
	}
	p->next = NULL;
	/////////////////////////////////////////////////////////////////
	//第二个链表
	head2 = (struct linklist*)malloc(SIZE);
	p = head2;
	scanf_s("%d", &l2);
	getchar();
	sum += l2;
	n = l2;
	while (n--)
	{
		q = (struct linkist*)malloc(SIZE);
		if (q == NULL)
			return 0;
		scanf_s("%d", &q->data);
		getchar();
		p->next = q;
		p = q;
	}
	p->next = NULL;
	//////////////////////////////////////////////
	//输出测试
	p = head1;
	while (p->next != NULL)
	{
		p = p->next;
		printf("%d ", p->data);
	}
	printf("\n");
	p = head2;
	while (p->next != NULL)
	{
		p = p->next;
		printf("%d ", p->data);
	}
	printf("\n");
	////////////////////////////////////////////////////////////////////////////////////
	//穿针连节点
	head3 = head1;
	p = head1->next;
	q = head2->next;
	r = head1;
	while (p&& q)
	{
		if (p->data <= q->data)
		{
			r->next = p;
			r = p;
			p = p->next;
		}
		else
		{
			r->next = q;
			r = q;
			q = q->next;
		}
	}
	r->next = p ? p : q;
	///////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////
	//输出测试
	p = head3;
	while (p->next != NULL)
	{
		p = p->next;
		printf("%d ", p->data);
	}
	printf("\n");
	p = head3;
	while (p->next != NULL)
	{
		p = p->next;
		printf("%d ", p->data);
	}
	printf("\n");
	////////////////////////////////////////////////////////////////////////////////////
	return 0;
}
发布了26 篇原创文章 · 获赞 0 · 访问量 92

猜你喜欢

转载自blog.csdn.net/qq_45812941/article/details/104413290