Description
(线性表)假设有两个按元素值递增次序排列的线性表,均以单链表形式存储。请编写算法将这两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
Input
输入长度n:5
输入数据:1 2 5 6 8
输入长度m:5
输入数据:
3 4 7 9 10
Output
10 9 8 7 6 5 4 3 2 1
Sample Input
4
7 9 10 11
4
8 12 13 14
Sample Output
14 13 12 11 10 9 8 7
【AC代码】:
#include <malloc.h>
#include <stdio.h>
typedef struct Node
{
int data;
struct Node *next;
} SqList;
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));
L->next=NULL;
}
void Insert(SqList *&L,char x)
{
/**尾插法建表*/
SqList *s,*p;
p=L;
while(p->next!=NULL)
p=p->next;
s=p;
p=(SqList *)malloc(sizeof(SqList));
p->data=x;
s->next=p;
p->next=NULL;
}
void Print(SqList *&L)
{
SqList *p=L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void sort(SqList *&L)
{
SqList *p,*pre,*q;
p=L->next->next; //p指向L的第2个数据节点
L->next->next=NULL; //构造只含一个数据节点的有序表
while(p!=NULL)
{
q=p->next; //q保存*p节点后继节点的指针
pre=L; //从有序表开头进行比较,pre指向插入*p的前驱节点
while(pre->next!=NULL&&pre->next->data>p->data)
pre=pre->next;//在有序表中找插入*p的前驱节点*pre
p->next=pre->next;//将*pre之后插入*p
pre->next=p;
p=q; //扫描原单链表余下的节点
}
}
int main()
{
SqList *L;
InitList(L);
int n;
scanf("%d",&n);
int i,a;
for(i=0; i<n; i++)
{
scanf("%d",&a);
Insert(L,a);
}
int m;
scanf("%d",&m);
for(i=n; i<n+m; i++)
{
scanf("%d",&a);
Insert(L,a);
}
sort(L);
Print(L);
free(L);
return 0;
}