兰州拼团网站建设/实训百度搜索引擎的总结
顺序表应用5:有序顺序表归并
Time Limit: 100 ms Memory Limit: 880 KiB
Submit Statistic Discuss
Problem Description
已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。
Input
输入分为三行:
第一行输入m、n(1<=m,n<=10000)的值,即为表A、B的元素个数;
第二行输入m个有序的整数,即为表A的每一个元素;
第三行输入n个有序的整数,即为表B的每一个元素;
Output
输出为一行,即将表A、B合并为表C后,依次输出表C所存放的元素。
Sample Input
5 3
1 3 5 6 9
2 4 10
Sample Output
1 2 3 4 5 6 9 10
Hint
Source
#include <stdio.h>
#include <stdlib.h>
struct st
{int data;struct st *next;
};
int main()
{int n,m,i;struct st *head,*tail,*head2,*q,*p;head=(struct st*)malloc(sizeof(struct st));head->next=NULL;head2=(struct st*)malloc(sizeof(struct st));head2->next=NULL;tail=head;scanf("%d%d",&m,&n);for(i=0; i<m; i++){p=(struct st*)malloc(sizeof(struct st));scanf("%d",&p->data);p->next=NULL;tail->next=p;tail=p;}tail=head2;for(i=0; i<n; i++){p=(struct st*)malloc(sizeof(struct st));scanf("%d",&p->data);p->next=NULL;tail->next=p;tail=p;}p=head->next;q=head2->next;tail=head;while(p&&q){if(p->data<q->data){tail->next=p;tail=p;p=p->next;}else{tail->next=q;tail=q;q=q->next;}}while(p){tail->next=p;tail=p;p=p->next;}while(q){tail->next=q;tail=q;q=q->next;}p=head->next;while(p){printf("%d ",p->data);p=p->next;}printf("\n");return 0;
}
C++
#include <iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#define N 1000010
using namespace std;
typedef struct st
{int data;struct st *next;
} tree;
tree *h1,*h2;
tree *creat(int n)
{tree *h,*tail,*p;h=new tree;h->next=NULL;tail=h;for(int i=0;i<n;i++){p=new tree;cin>>p->data;p->next=NULL;tail->next=p;tail=p;}return h;
}
tree *pre(tree *h1,tree *h2)
{tree *p1,*p2,*tail;p1=h1->next;p2=h2->next;tail=h1;while(p1&&p2){if(p1->data<p2->data){tail->next=p1;tail=p1;p1=p1->next;tail->next=NULL;}else{tail->next=p2;tail=p2;p2=p2->next;tail->next=NULL;}}if(p1)tail->next=p1;else tail->next=p2;return h1;
}
int main()
{int n,m;cin>>n>>m;tree *h,*p;h1=creat(n);h2=creat(m);h=pre(h1,h2);p=h->next;while(p){if(p->next==NULL)printf("%d\n",p->data);else printf("%d ",p->data);p=p->next;}return 0;
}