#include<malloc.h>
#include<iostream>
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
using namespace std;
//————————————————————顺序表————————————————————————
typedef int ElemType;
typedef struct {
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量(以sizeof(ElemType)为单位)
}List;
/*
typedef struct {
ElemType data;
struct LNode *next;
}LNode;
*/
bool InitList(List &L)
{
//创建新的链表,成功则返回链表的基址
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem) return false; //存储分配失败
L.length = 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
return true;
}//InitList
int ListLength(List &L)
{
//返回列表的长度
return L.length;
}//ListLength
void GetElem(List L, int i, ElemType &e)
{
//用e返回L中第i个数据元素的值
e = L.elem[i - 1];
}//GetElem
bool ListInsert(List &L, int i, ElemType e)
{
//在L中的第i个位置之前插入新的数据元素e,L的长度加1
//i的合法值为1 <= i <= ListLength(L)+1
//成功则返回TRUE,失败返回FALSE
if (i<1 || i>L.length + 1)return false; //i值不合法
if (L.length >= L.listsize) { //当前存储空间已满,增加分配
ElemType *newbase = (ElemType*)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)return false; //存储分配失败
L.elem = newbase; //新基址
L.listsize += LISTINCREMENT; //增加存储容量
}
ElemType *q = &(L.elem[i - 1]); //q为插入位置
for (ElemType *p = &(L.elem[L.length-1]); p >= q; --p) *(p + 1) = *p;
//插入位置及之后的元素右移
*q = e; //插入e
++L.length;
return true;
}//ListInsert
void MergeList(List La, List Lb, List &Lc)
{
//已知线性表La和Lb中的数据元素按值非递减排列
//归并La和Lb得到新的线性表Lc,Lc的数据元素也按值非递减排列
int i, j, k;
ElemType ai, bj;
InitList(Lc);
i = j = 1; k = 0;
int La_len = ListLength(La); int Lb_len = ListLength(Lb);
while ((i <= La_len) && (j <= Lb_len)) {//La和Lb均非空
GetElem(La, i, ai); GetElem(Lb, j, bj);
if (ai <= bj) { ListInsert(Lc, ++k, ai); ++i; }
else { ListInsert(Lc, ++k, bj); ++j; }
}
while (i <= La_len) {
GetElem(La, i++, ai); ListInsert(Lc, ++k, ai);
}
while (j <= Lb_len) {
GetElem(Lb, j++, bj); ListInsert(Lc, ++k, bj);
}
}//MergeList
//————————————————————顺序表————————————————————————
int main()
{
List La,Lb,Lc;
int i, j = 0, k = 0;
InitList(La);
InitList(Lb);
for (int i = 1; i < 10; i += 2) ListInsert(La, j++, i);
for (int i = 0; i < 10; i += 2) ListInsert(Lb, k++, i);
MergeList(La, Lb, Lc);
//for (i = 0; i < La.length; i++) cout << La.elem[i] << endl;
//for (i = 0; i < Lb.length; i++) cout << Lb.elem[i] << endl;
//cout << Lb.length<<La.length << endl;
for (i = 0; i < Lc.length; i++) cout << Lc.elem[i]<< endl;
}