您的位置:首页 > 理论基础 > 数据结构算法

两个有序顺序表合并

2016-07-07 11:52 281 查看
这是在做数据结构考研题目时遇到的题。

在这里记录一下,其中有上网参考大家的代码。

题目如下:

/*

题目:编写算法,将两个非递减有序顺序表A和B合成一个新的非递减有序顺序表C。

已知顺序表A和B的元素个数分别为m,n。其中顺序表采用动态分配内存空间,其定义如下:

typedef struct{

ElemType *elem; //存储空间基址

int length; //当前长度

int listsize; //当前分配的存储容量

}Sqlist;

*/



[code]#include
#include "stdlib.h"
#include
typedef int ElemType;//定义ElemType为int类型
#define LIST_INIT_SIZE 100
#define error 0
#define ok 1
typedef struct{
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量
}Sqlist;

int InitList_sq(Sqlist &A)
{
A.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!A.elem)
return error;
A.length = 0;
A.listsize = LIST_INIT_SIZE;
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;
}

void merge( Sqlist A,Sqlist B, Sqlist &C)
{
int i = 0, j = 0, k = 0; // A B C三个数组指针 i,j,k;
while (i < A.length&&j < B.length) //循环退出的条件
{
if (A.elem[i]B.elem[j])
{
C.elem[k] = B.elem[j];
j++;
k++;
}
}
while (i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构