顺序表应用5:有序顺序表归并
Time Limit: 100MS Memory limit: 800K
题目描述
已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。
输入
输入分为三行:
第一行输入m、n的值,即为表A、B的元素个数;
第二行输入m个有序的整数,即为表A的每一个元素;
第三行输入n个有序的整数,即为表B的每一个元素;
第一行输入m、n的值,即为表A、B的元素个数;
第二行输入m个有序的整数,即为表A的每一个元素;
第三行输入n个有序的整数,即为表B的每一个元素;
输出
输出为一行,即将表A、B合并为表C后,依次输出表C所存放的元素。
示例输入
5 3 1 3 5 6 9 2 4 10
示例输出
1 2 3 4 5 6 9 10
提示
来源
示例程序
#include<bits/stdc++.h> using namespace std; struct node { int *elem; int len; //结构体中不能赋值 int listsize; }; int Creat(node &L) { L.elem=new int[1000]; if(!L.elem)exit(0); L.len=0; L.listsize=1000; return 1; } int Insert(node &L,int i,int e) { if(L.len>=L.listsize) { int *newbase=(int *)realloc(L.elem,(L.listsize+10)*sizeof(int)); L.elem=newbase; L.listsize=L.len+10; } int *p=&(L.elem[i-1]); for(int *q=p;q<=&(L.elem[L.len-1]);p++) { *(q+1)=*(q); } *p=e; L.len++; return 0; } int main() { int n,m; while(~scanf("%d%d",&n,&m)) { node L1,L2,L; Creat(L1); Creat(L2); Creat(L); for(int i=1;i<=n;i++) { int dd; scanf("%d",&dd); Insert(L1,i,dd); } for(int i=1;i<=m;i++) { int dd; scanf("%d",&dd); Insert(L2,i,dd); } //cout<<"$"; int *p1=L1.elem; int *p2=L2.elem; int num1=0,num2=0,num=0; while((num1<L1.len)&&(num2<L2.len)) { num++; if(*p1>*p2) { Insert(L,num,*p2); p2++; num2++; } else { num1++; Insert(L,num,*p1); p1++; } } while(num1<L1.len) { num++; num1++; Insert(L,num,*p1); p1++; } while(num2<L2.len) { num++; num2++; Insert(L,num,*p2); p2++; } int kk=1; for(int *p=L.elem;p<=&(L.elem[L.len-1]);p++) { if(kk) kk=0; else printf(" "); printf("%d",*p); } printf("\n"); } }
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *next;
};
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
node *head,*tail,*head1;
head=new node;
head->next=NULL;
tail=head;
for(int i=0;i<n;i++)
{
node *p=new node;
p->next=NULL;
scanf("%d",&p->data);
tail->next=p;
tail=p;
}
head1=new node;
head1->next=NULL;
tail=head1;
for(int i=0;i<m;i++)
{
node *p=new node;
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
node *p=head->next;
node *q=head1->next;
tail=head;
tail->next=NULL; //head也指向空了
node *t;
//printf("%d\n",head->next);
while(p&&q)
{
if(p->data<q->data)
{
t=p;
p=p->next;
}
else
{
t=q;
q=q->next;
}
tail->next=t;
tail=t;
}
if(q)tail->next=q;
if(p)tail->next=p;
tail=head->next;
while(tail)
{
printf("%d ",tail->data);
tail=tail->next;
}
}
return 0;
}