原题链接
考研内容复习
链表
# include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
void Initialize(struct node **head)
{
(*head) = (struct node *)malloc(sizeof(struct node));
(*head)->next=NULL;
}
void Insert(struct node **head, int a)
{
struct node *p;
p = (struct node *)malloc(sizeof(struct node));
p->data = a;
(*head)->next = p;
(*head) = p;
p->next = NULL;
}
struct node * Create(struct node *head, int N)
{
struct node *tail;
tail = head;
for(int i=0; i<N; i++)
{
int a;
cin>>a;
Insert(&tail,a);
}
return head;
}
void Print(struct node *head)
{
struct node *p;
p = head->next;
bool flag = true;
while(p)
{
if(flag)
{
cout<<p->data;
flag=false;
}
else
cout<<' '<<p->data;
p=p->next;
}
cout<<endl;
}
struct node * Combine(struct node *head1, struct node *head2)
{
struct node *head, *tail;
Initialize(&head);
tail = head;
struct node *p, *q;
p = head1->next;
q = head2->next;
while(p&&q)
{
if(p->data<q->data)
{
Insert(&tail,p->data);
p = p->next;
}
else
{
Insert(&tail,q->data);
q = q->next;
}
}
if(p)
{
tail->next = p;
}
else
{
tail->next = q;
}
return head;
}
int main()
{
int M, N;
cin>>M>>N;
struct node *head1, *head2;
Initialize(&head1);
Initialize(&head2);
head1 = Create(head1,M);
head2 = Create(head2,N);
struct node *head = Combine(head1,head2);
Print(head);
return 0;
}