-
题目描述:
-
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(hint: 请务必使用链表。)
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为两个整数n和m(0<=n<=1000, 0<=m<=1000):n代表将要输入的第一个链表的元素的个数,m代表将要输入的第二个链表的元素的个数。
下面一行包括n个数t(1<=t<=1000000):代表链表一中的元素。接下来一行包含m个元素,s(1<=t<=1000000)。
-
输出:
-
对应每个测试案例,
若有结果,输出相应的链表。否则,输出NULL。
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Link
{
int data;
struct Link *next;
}Node;
//构建带头结点的链表
Node *create(int n)
{
Node *head,*p,*s;
head = (Node *)malloc(sizeof(Node));
p = head;
for(int i = 0; i < n; i++)
{
s = (Node *)malloc(sizeof(Node));
scanf("%d",&s->data);
p->next = s;
p = s;
}
p->next = NULL;
return head;
}
//生成的是带头结点的链表
Node *combine(Node *head1,Node *head2)
{
Node *head = (Node *)malloc(sizeof(Node));
Node *p = head1->next, *q = head2->next, *r;
r = head;
while(p != NULL & q != NULL)
{
if(p->data <= q->data)
{
r->next = p;
r = p;
p = p->next;
}
else
{
r->next = q;
r = q;
q = q->next;
}
}
while(p != NULL)
{
r->next = p;
r = p;
p = p->next;
}
while(q != NULL)
{
r->next = q;
r = q;
q = q->next;
}
return head;
}
//打印带头节点的链表
void print(Node *head)
{
Node *p = head->next;
while(p != NULL)
{
if(p == head->next)
printf("%d",p->data);
else
printf(" %d",p->data);
p = p->next;
}
printf("\n");
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m) != EOF)
{
if(n == 0 && m == 0)
printf("NULL\n");
else if(n == 0)
{
Node *head2 = create(m);
print(head2);
}
else if(m == 0)
{
Node *head1 = create(n);
print(head1);
}
else
{
Node *head1 = create(n);
Node *head2 = create(m);
Node *head = combine(head1,head2);
print(head);
}
}
}