一、解析
线性表的一种,是与内存结构对应的,故称之为线性顺序表。//数据结构第二周目,整理下以前的代码 。对应书上的p19-p26。
二、存储结构
typedef struct {
ElemType *elem;//存储空间基址
int length;//当前长度
int listSize;//当前分配的储存容量
}Sqlist;
三、操作
//顺序表 2017-04-23
// c2-1.h 线性表的动态分配顺序存储结构。在教科书第22页
#define LIST_INIT_SIZE 30 // 线性表存储空间的初始分配量
#define LIST_INCREMENT 2 // 线性表存储空间的分配增量
typedef struct {
ElemType *elem;//存储空间基址
int length;//当前长度
int listSize;//当前分配的储存容量
}Sqlist;
Status InitList_Sq(Sqlist &L){
//构造一个空的线性表L。
L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
//存储分配失败
if (!L.elem)
{
exit(OVERFLOW);
}
//当前的数据长度
L.length = 0;
//当前分配的空间长度
L.listSize = LIST_INIT_SIZE;
return OK;
}
Status ListInsert_Sq(Sqlist &L, int i, ElemType e){
//在顺序表上的第i个元素和第i-1个元素中间插入元素
if (L.length >= L.listSize)
{
//空间满了 要再次分配
printf("空间满了");
return ERROR;
}
//插入的位置是边界的情况 这种情况不用把数字往后移动
if (i == L.length)
{
L.elem[i] = e;
L.length++;
return OK;
}
//判断i位置的合法性[0,L.length]
if (!(i >= 0 && i <= L.length - 1))
{
printf("插入的元素非法");
return ERROR;
}
//对元素i位置进行插入,将元素往后移动
for (int j = L.length; j >= i; j--)
{
L.elem[j] = L.elem[j - 1];
}
//插入元素 长度加1
L.elem[i] = e;
L.length++;
return OK;
}
Status ListDelete_Sq(Sqlist &L, int i, ElemType &e){
//在顺序线性表L中删除第i个元素,并用e返回其值
//判断i位置的合法性[0,L.length]
if (!(i >= 0 && i <= L.length - 1))
{
printf("删除的元素位置非法");
return ERROR;
}
e = L.elem[i];
for (int j = i; j < L.length - i - 1; j++)
{
L.elem[j] = L.elem[j + 1];
}
L.length--;
return OK;
}
void MergeList_Sq(Sqlist La, Sqlist Lb, Sqlist &Lc){
//La与Lb是以递增的形式排列好的 现在合并两个List表 返回Lc
InitList_Sq(Lc);
int indexA = 0, indexB = 0, indexC = 0;//指向La,Lb的位置索引
int La_len = La.length;
int Lb_len = Lb.length;
while (indexA <= La.length && indexB <= Lb.length)
{
ElemType elemA = La.elem[indexA];
ElemType elemB = La.elem[indexB];
if (elemA < elemB)
{
//将小的值插入LcList中 A中的值小
ListInsert_Sq(Lc, indexC++, elemA);
indexA++;
}
else
{
ListInsert_Sq(Lc, indexC++, elemB);
indexB++;
}
}
//循环完后将剩下的都数都放进Lc中
while (indexA <= (La.length - 1))
{
//如果A还没合并完的情况
ElemType temp = La.elem[indexA];
ListInsert_Sq(Lc, indexC++, temp);
indexA++;
}
while (indexB <= (Lb.length - 1))
{
ElemType temp = La.elem[indexB];
ListInsert_Sq(Lc, indexC++, temp);
indexB++;
}
}
void PrintList(Sqlist L){
//打印顺序表
for (int i = 0; i < L.length; i++)
{
printf("%d:", L.elem[i]);
}
printf("\n当前的list的长度%d\n", L.length);
}
四、执行
Sqlist list;
InitList_Sq(list);
ListInsert_Sq(list, 0, 1);
PrintList(list);
ListInsert_Sq(list, 0, 2);
PrintList(list);
ListInsert_Sq(list, 0, 3);
ListInsert_Sq(list, 0, 4);
PrintList(list);
int e;
ListDelete_Sq(list,2, e);
PrintList(list);
输出:1:
当前的list的长度1
2:1:
当前的list的长度2
4:3:2:1:
当前的list的长度4
4:3:2:
当前的list的长度3
请按任意键继续. . .