单链表的归并

Description

假设两个按元素值非递减有序排列的线性表A和B,均以单链表作为存储结构,试编写程序,将A表和B表归并成一个按元素值非递增有序排列的线性表C,并要求利用原表(即A表和B表的)结点空间存放表C。

Input

第一行输入两个正整数m,n(m,n<=100),用空格分开,分别表示线性表A和B中元素个数,其后两行分别输入单链表A和B。

Output

输出单链表C。

  • Sample Input 
    5 5
    1 3 7 12 16
    2 6 7 13 20
  • Sample Output
    20 16 13 12 7 7 6 3 2 1

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int num;
	struct node* pre;
	struct node* next;
}node;

node* creat(int n)
{
	node *p, *q, *head;

	head = (node* )malloc(sizeof(node));
	head->pre = NULL;
	p = head;
	for(int i = 0;i < n;i++)
	{
		q=(node* )malloc(sizeof(node));
		scanf("%d",&(q->num));
		p->next = q;
		q->pre = p;
		p=q;
	}
	p->next = NULL;
	return head;
}

node* guibing(node* head1, node* head2)
{
	node* head,*p,*q,*m,*n;
	head=(node* )malloc(sizeof(node));
	head->pre = NULL;
	n = head;
	p = head1->next;
	q = head2->next;
	while(p&&q)
	{
		if(p->num < q->num)
		{
			n->next = p;
			p->pre = n;
			n = p;
			p = p->next;
		}
		else
		{
			n->next = q;
			q->pre = n;
			n = q;
			q = q->next;
		}
	}
	if(p)
	{
		n->next = p;
		p->pre = n;
		n = p;
	}
	else
	{
		n->next = q;
		q->pre = n;
		n = q;
	}
	while(1)
	{
		if(n->next == NULL)
		{
			break;
		}
		n=n->next;
	}
	return n;
}

node* getout(node* tail)
{
	while(1)
	{
		if(tail->pre->pre == NULL)
		{
			printf("%d\n", tail->num);
			break;
		}
		else
		{
			printf("%d ", tail->num);
			tail = tail->pre; 
		}
	}
	return 0;
}

int main()
{
	int n, m;
	node *head1, *head2, *tail;
	scanf("%d%d",&n,&m);
	head1 = creat(n);
	head2 = creat(m);
	tail = guibing(head1,head2);
	getout(tail);
	return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值