#include <iostream>
#include <cstdio>
#include <stdlib.h>//malloc函数头文件
using namespace std;
typedef struct Node
{
int data;
struct Node * next;
} LNode,*LinkList;//直接定义节点指针,这样代码指针不会出现*,简洁
LinkList built(int n)
{
LinkList p,r,list;
list=(LinkList)malloc(sizeof(LNode));
list->next=NULL;
for(int i=0; i<n; i++)
{
int d;
scanf("%d",&d);
p=(LinkList)malloc(sizeof(LNode));
p->data=d;
p->next=NULL;
if(list->next==NULL)
list->next=p;
else
r->next=p;
r=p;
}
return (list);
}
LinkList ListMerger(LinkList ListA,LinkList ListB)//两个链表的合并
{
LinkList pa,pb,pc,ListC;
ListC=(LinkList)malloc(sizeof(LNode));
pa=ListA->next;
pb=ListB->next;
pc=ListC;
pc->next=NULL;
while(pa&&pb)
{
if(pa->data<pb->data)
{
pc->next=pa;
pc=pa;
pa=pa->next;
}
else
{
pc->next=pb;
pc=pb;
pb=pb->next;
}
}
pc->next=pa?pa:pb;//指向剩余的链表
return ListC;
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
if(!n&&!m)
{
printf("NULL\n");
continue;
}
LinkList ra=built(n);
LinkList rb=built(m);
LinkList t=ListMerger(ra,rb);
if(t->next!=NULL)t=t->next;
while(t->next!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<t->data<<endl;
}
return 0;
}
非递减合并两个有序单链表
最新推荐文章于 2023-09-15 19:38:15 发布