-
题目描述:
-
输入两个递增的序列,输出合并这两个序列后的递增序列。
-
输入:
-
每个测试案例包括3行:
第一行为1个整数n(1<=n<=1000000)表示这两个递增序列的长度。
第二行包含n个整数,表示第一个递增序列。
第三行包含n个整数,表示第二个递增序列。
-
输出:
-
对应每个测试案例,输出合并这两个序列后的递增序列。
-
样例输入:
-
41 3 5 72 4 6 8
-
样例输出:
-
1 2 3 4 5 6 7 8
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<stack>
#include<vector>
#include<string.h>
#include<limits.h>
#include<stdlib.h>
#define ABS(x) ((x)>=0?(x):(-(x)))
using namespace std;
struct Node
{
int val;
Node *next;
Node(int value):val(value),next(NULL){}
};
void list_construct(Node **head, int len)
{
int i;
int val;
Node *p;
for(i=0;i<len;++i)
{
cin>>val;
if(NULL==*head)
{
*head = new Node(val);
p = *head;
}
else
{
p->next = new Node(val);
p = p->next;
}
}
return;
}
void list_print(Node *head)
{
while(head)
{
cout<<head->val;
head = head->next;
}
return;
}
int get_length(Node *head)
{
int len = 0;
while(head)
{
len++;
head = head->next;
}
return len;
}
Node* sort_list(Node *list1, Node *list2)
{
Node *head = NULL;
Node *p;
while(list1&&list2)
{
if(list1->val<list2->val)
{
if(head==NULL)
{
head = list1;
p = head;
list1 = list1->next;
p->next = NULL;
}
else
{
p->next = list1;
list1 = list1->next;
p = p->next;
p->next = NULL;
}
}
else
{
if(head==NULL)
{
head = list2;
p = head;
list2 = list2->next;
p->next = NULL;
}
else
{
p->next = list2;
list2 = list2->next;
p = p->next;
p->next = NULL;
}
}
}
if(list1==NULL)
p->next = list2;
else
p->next = list1;
return head;
}
void delete_list(Node *list)
{
Node *p = list;
while(p)
{
p = list->next;
delete list;
list = p;
}
}
int main()
{
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
int n;
Node *list1, *list2;
Node *head,*q;
while(cin>>n)
{
list1 = list2 = NULL;
list_construct(&list1, n);
list_construct(&list2, n);
head = sort_list(list1,list2);
q = head;
while(head)
{
cout<<head->val;
if(head->next)
cout<<' ';
head = head->next;
}
cout<<endl;
delete_list(q);
}
fclose(stdin);
fclose(stdout);
return 0;
}