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;
}