同SDUT-OJ-F - 数据结构实验之链表四:有序链表的归并
#include<bits/stdc++.h>
using namespace std;
struct node
{
node *next;
int data;
};
void mergerlist(node *l1, node *l2, node *l)
{
node *t, *p, *q;
t = l;
p = l1->next;
q = l2->next;
while(p && q)
{
if(p->data < q->data)
{
t->next = p;
t = p;
p = p->next;
}
else
{
t->next = q;
t = q;
q = q->next;
}
if(p)
t->next = p;
else
t->next = q;
}
}
void creat(node *l, int n)
{
node *p, *t;
t = l;
int x;
for(int i = 0; i < n; i++)
{
p = (node *)malloc(sizeof(node));
cin>>x;
p->data = x;
t->next = p;
p->next = NULL;
t = p;
}
}
void print(node *l)
{
node *p;
p = l->next;
while(p)
{
if(p->next == NULL)
cout<<p->data;
else
cout<<p->data<<" ";
p = p->next;
}
}
int main()
{
node *l, *l1, *l2;
int n, m;
l = (node *)malloc(sizeof(node));
l1 = (node *)malloc(sizeof(node));
l2 = (node *)malloc(sizeof(node));
l->next = NULL;
l1->next = NULL;
l2->next = NULL;
cin>>n>>m;
creat(l1, n);
creat(l2, m);
mergerlist(l1, l2, l);
print(l);
}
|