8577 合并顺序表
时间限制:1000MS 代码长度限制:10KB
提交次数:5339 通过次数:2251
题型: 编程题 语言: G++
Description
若线性表中数据元素相互之间可以比较,且数据元素在表中按值递增或递减,则称该表为有序表。
编写算法,将两个非递减有序顺序表A和B合并成一个新的非递减有序顺序表C。
输入格式
第一行:顺序表A的元素个数
第二行:顺序表A的各元素(非递减),用空格分开
第三行:顺序表B的元素个数
第四行:顺序表B的各元素(非递减),用空格分开
输出格式
第一行:顺序表A的元素列表
第二行:顺序表B的元素列表
第三行:合并后顺序表C的元素列表
输入样例
5
1 3 5 7 9
5
2 4 6 8 10
输出样例
List A:1 3 5 7 9
List B:2 4 6 8 10
List C:1 2 3 4 5 6 7 8 9 10
方法一:(简便但难理解)
int LIST_merge(SqList &A ,SqList &B ,SqList &C)
{
C.length=A.length+B.length;
int i=0,j=0,k=0;
while(i<A.length&&j<B.length)
{
if(A.elem[i]<B.elem[j])
{
C.elem[k++]=A.elem[i++];
}
else
C.elem[k++]=B.elem[j++];
}
while(i<A.length)
C.elem[k++]=A.elem[i++];
while(j<B.length)
C.elem[k++]=B.elem[j++];
return OK;
}
方法二:
#include<stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
typedef struct
{
int *elem;
int length;
int listsize;
} SqList;
int InitList_Sq(SqList &L)
{
// 算法2.3,构造一个空的线性表L,该线性表预定义大小为LIST_INIT_SIZE
// 请补全代码
L.elem=new ElemType [LIST_INIT_SIZE];
if(!L.elem) return ERROR;
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}
int FillList_Sq(SqList &L)
{
int listlength;
scanf("%d", &listlength);
int temp;
int i;
for (i = 0; i < listlength; i++)
{
scanf("%d", &temp);
L.elem[i] = temp;
L.length++; //
}
return OK;
}
int Load_Sq(SqList &L)
{
// 输出顺序表中的所有元素
int i;
if(L.length==0) printf("The List is empty!"); // 请填空
else
{
for(i=0; i<L.length; i++) printf("%d ",L.elem[i]); // 请填空
}
printf("\n");
return OK;
}
int ListInsert_Sq(SqList &L,int i,int e)
{
// 算法2.4,在顺序线性表L中第i个位置之前插入新的元素e
// i的合法值为1≤i≤L.length +1
// 请补全代码
if((i<1)||(i>L.length+1))
return ERROR;
if(i>LIST_INIT_SIZE)
return ERROR;
for(int j=L.length-1; j>=i-1; j--)
{
L.elem[j+1]=L.elem[j];
}
L.elem[i-1]=e;
L.length++;
return OK;
}
int ListDelete_Sq(SqList &L,int i, int &e)
{
// 算法2.5,在顺序线性表L中删除第i个位置的元素,并用e返回其值
// i的合法值为1≤i≤L.length
// 请补全代码
if((i<1)||(i>L.length))
return ERROR;
e=L.elem[i-1];
for(int j=i-1; j<L.length-1; j++)
L.elem[j]=L.elem[j+1];
L.length--;
return OK;
}
int LIST_merge(SqList &A ,SqList &B ,SqList &C)
{
C.length=0;
int i=0,j=0,k=0;
while(i<A.length&&j<B.length)
{
if(A.elem[i]>B.elem[j])
{
C.elem[k]=B.elem[j];
k++;
j++;
C.length++;
}
else
{
C.elem[k]=A.elem[i];
k++;
i++;
C.length++;
}
}
if(j<B.length)
{
while(j<B.length)
{
C.elem[k]=B.elem[j];
k++;
j++;
C.length++;
}
}
if(i<A.length)
{
while(i<A.length)
{
C.elem[k]=A.elem[i];
k++;
i++;
C.length++;
}
}
return OK;
}
int main()
{
SqList A,B,C;
InitList_Sq(A);
InitList_Sq(B);
InitList_Sq(C);
FillList_Sq(A);
FillList_Sq(B); //填充线性表
printf("List A:");
Load_Sq(A);
printf("List B:");
Load_Sq(B);
LIST_merge(A,B,C);
printf("List C:");
Load_Sq(C);
return 0;
}