#include<stdio.h>
#include<stdlib.h>
typedef struct _Node
{
int data;
struct _Node *next;
}Node;
typedef struct _list{
Node *head;
}List;
void add(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=NULL;
Node *last=pList->head;
if(last)
{
while(last->next)
{
last=last->next;
}
last->next=p;
}
else
pList->head=p;
}
void add2(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=pList->head;
pList->head=p;
}
void add3(List *pList,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=number;
p->next=NULL;
if(pList->head==NULL||p->data<pList->head->data)
{
p->next=pList->head;
pList->head=p;
}
else
{
Node *q=pList->head;
while(q->next&&p->data>q->next->data)
{
q=q->next;
}
if(q->next==NULL)
{
q->next=p;
}
else
{
p->next=q->next;
q->next=p;
}
}
}
void showL(List *pList)
{
Node *p;
for(p=pList->head;p;p=p->next)
{
printf("%d ",p->data);
}
}
List Merge(List *pList1,List *pList2)
{
Node *p,*q;
p=pList1->head;
q=pList2->head;
List L;
L.head=NULL;
while(p&&q)
{
if(p->data<q->data)
{
add3(&L,p->data);
p=p->next;
}
else
{
add3(&L,q->data);
q=q->next;
}
}
if(p==NULL)
{
while(q)
{
add3(&L,q->data);
q=q->next;
}
}
else if(q==NULL)
{
while(p)
{
add3(&L,p->data);
p=p->next;
}
}
return L;
}
int main()
{
List L1,L2,L3;
L1.head=NULL;
L2.head=NULL;
L3.head=NULL;
int n,temp,m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%d",&temp);
add3(&L1,temp);
}
for(int i=0;i<m;i++)
{
scanf("%d",&temp);
add3(&L2,temp);
}
L3=Merge(&L1,&L2);
// int m;
//scanf("%d",&m);
//ldelete(&L,m);
showL(&L3);
}
链表的归并
最新推荐文章于 2023-11-22 18:40:57 发布