/*
线性表的顺序存储表示
优点:1.无须为表示表中的逻辑关系增加额外的存储空间
2. 可以快速存取表中任意位置的元素
缺点:1.插入和删除的操作需要移动大量元素 O(n)
2.当线性表长度变化较大,难以确定存储空间的容量
3.造成存储空间“碎片”
*/
#include<iostream>
typedef char date;
// 顺序线性 表最大长度
const int MaxSize = 20;
// 数据元素
struct Book
{
date isbn[MaxSize];
date name[MaxSize];
float price ;
};
// 线性表
struct Sqlist
{
Book* elem;
int length;
};
// 线性表初始化
int InitList_Sq(Sqlist& L)
{
L.elem = new Book[MaxSize];
if (!L.elem)
{
std::cout << "存储分配失败!!!"<<std::endl;
return 0;
}
L.length = 0;
return 1;
}
// 线性表销毁
void DestroyList(Sqlist& L)
{
if (!L.elem)
delete[] L.elem;
}
// 线性表清除
void ClearList(Sqlist& L)
{
L.length = 0;
}
// 获得线性表长度
int GetLength(Sqlist& L)
{
return L.length;
}
// 判断线性表是否为空
int IsEmpty(Sqlist& L)
{
if (L.length == 0)
return 1;
return 0;
}
// 获得指定位置的元素
int GetElem(const Sqlist &L,int i , Book &temp)
{
if (i<1 || i>L.length)
return 0;
temp = L.elem[i - 1];
return 1;
}
// 按值查找
int ListInsert(const Sqlist& L, const Book &temp)
{
for(int i = 0;i<L.length;i++)
{
// 结构体不能直接比较
if(L.elem[i].price == temp.price)
return (i + 1);
}
return 0;
}
// 插入元素
int InsertList(Sqlist& L,int i, const Book& temp)
{
if (L.length == MaxSize)
return 0;
if(i<1||i>L.length+1)
return 0;
if (i <= L.length)
{
for (int j = L.length - 1; j > i - 1; j--)
{
L.elem[j + 1] = L.elem[j];
}
}
L.elem[i - 1] = temp;
L.length++;
return 1;
}
// 删除元素
int DeleteList(Sqlist& L, int i, Book& temp)
{
if (i<1 || i>L.length)
return 0;
// 取出删除的元素
temp = L.elem[i - 1];
if (i < L.length)
{
for (int j = i; j< L.length; j++)
{
L.elem[j-1] = L.elem[j];
}
}
L.length--;
return 1;
}
int main(void)
{
Sqlist list;
InitList_Sq(list);
DestroyList(list);
return 0;
}