#include <stdio.h>
#include <stdlib.h>
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
typedef int ElemType; //自定义顺序表的数据元素为字符型
//顺序表的存储结构定义
typedef struct
{
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量(以sizeof(ElemType)为单位)
} SqList;
//顺序表的初始化
void InitList_Sq(SqList *L)
{
L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); //分配存储空间
if (!L->elem)
{ //存储分配失败
exit(0); //退出
}
else
{ //构造一个空表
L->length = 0;
L->listsize = LIST_INIT_SIZE; //给线性表分配空间
printf(“顺序表已完成初始化\n”);
}
}
//为顺序表赋值
void FuZhi(SqList *L, int i, int e)
{
ElemType *insert, *p;
insert = &(L->elem[i]); //i从0开始
*insert = e;
L->length++; //赋值后表长要+1
}
//合并
void HbList_Sq(SqList *L1, SqList *L2, SqList *L3)
{
ElemType *w, *q, *p;
int ab = 0;
for (int i = 0; i < L1->length; i++)
{
q = &(L1->elem[i]);
p = &(L3->elem[i]);
*p = *q;
L3->length++;
}
for (int b = L3->length; b < (L1->length + L2->length); b++)
{
w = &(L2->elem[ab]);
p = &(L3->elem[b]);
*p = *w;
ab++;
L3->length++;
}
}
//排序
void Order(SqList *L)
{
int temp = 0; //存储中间值
ElemType *p, *q, *w;
for (int i = 0; i < L->length; i++)
{
for (int j = i; j < L->length; j++)
{
q = &(L->elem[i]);
p = &(L->elem[j]);
if (*q >= *p)
{
temp = *q;
*q = *p;
*p = temp;
}
}
}
}
//打印顺序表
void show_list(SqList *L)
{
int i;
for (i = 0; i < L->length; i++)
{
printf("%d ", L->elem[i]);
}
}
int main()
{
int a = 1;
int b = 3;
int c = 5;
int d = 7;
int e = 9;
int f = 2;
int g = 3;
int h = 6;
SqList L1, L2, L3;
InitList_Sq(&L1);
InitList_Sq(&L2);
InitList_Sq(&L3);
FuZhi(&L1, 0, a);
FuZhi(&L1, 1, b);
FuZhi(&L1, 2, c);
FuZhi(&L1, 3, d);
FuZhi(&L1, 4, e);
FuZhi(&L2, 0, f);
FuZhi(&L2, 1, g);
FuZhi(&L2, 2, h);
printf("顺序表L1的数据为: ");
show_list(&L1);
printf("\n");
printf("顺序表L2的数据为: ");
show_list(&L2);
printf("\n");
HbList_Sq(&L1, &L2, &L3);
printf("合并后的顺序表为: ");
show_list(&L3);
printf("\n");
Order(&L3);
printf("排序后的顺序表为: ");
show_list(&L3);
return 0;
}
运行结果,将表1(1 3 5 7 9),表2(2 3 6)的数据元素合并到表3,并排序