線形テーブルの順序は、C ++の実装を表します
1つは、線形テーブルの定義と特性です。
1.線形テーブルの定義
2.リニアメーターの特徴
次に、線形テーブルのシーケンシャルストレージ表現
1.シーケンシャルストレージの定義
2.シーケンシャルストレージの例
3.シーケンシャルストレージの長所と短所
第三に、線形テーブル順序の実現
ここで、本は本の情報を保存する線形テーブルを実現するための基本的な要素です。
#include<iostream>
using namespace std;
#define MaxSize 50 //线性表最大长度
typedef struct{
//创建一个表示图书信息结构体
string name; //书名
int ISBN; //书号
float price; //价格
}Book;
class SqList
{
public:
SqList();
int Clear();
int Insert(int i, Book b);
Book GetElem(int i);
int Delete(int i);
bool IsEmpty();
int GetLength();
int Find(Book b);
~SqList();
private:
int length; //线性表长度
Book *elem; //存储图书信息的数组
};
SqList::SqList() //初始化线性表
{
elem = new Book[MaxSize];
length = 0;
}
int SqList::Clear() //清空线性表
{
length = 0;
return 1;
}
int SqList::Insert(int i,Book b) //将b插入到第i个位置
{
if(i<1||i>length+1||length==MaxSize)
{
return 0;
}
else
{
for(int j=length; j>i; --j)
{
elem[j] = elem[j-1];
}
elem[i-1] = b;
length++;
return 1;
}
}
Book SqList::GetElem(int i) //获取线性表中第i个元素
{
if(i<1||i>length)
{
Book b;
b.name = "NULL";
b.ISBN = 0;
b.price = 0;
return b;
}
else
{
return elem[i-1];
}
}
int SqList::Delete(int i) //删除表中第i个元素
{
if(i<1||i>length)
{
return 0;
}
else
{
for(int j=i-1; j<length-1; ++j)
{
elem[j] = elem[j+1];
}
length--;
return 1;
}
}
bool SqList::IsEmpty() //判断线性表是否为空
{
return length==0?0:1;
}
int SqList::GetLength() //返回线性表的长度
{
return length;
}
int SqList::Find(Book b) //在线性表中查找与b相同的元素
{
for(int i=0; i<length; ++i)
{
if(b.name==elem[i].name&&b.ISBN==elem[i].ISBN&&b.price==elem[i].price)
{
return i+1;
}
}
return 0;
}
SqList::~SqList() //销毁线性表
{
if(elem)
{
delete elem;
elem = NULL; //delete后指针elem的地址空间被释放,但不会被赋值为空,所以手动赋值为空
}
}
int main()
{
Book b1,b2,b3;
b1.ISBN = 1;
b1.name = "first";
b1.price = 10;
b2.ISBN = 2;
b2.name = "second";
b2.price = 20;
b3.ISBN = 3;
b3.name = "third";
b3.price = 30;
SqList L;
L.Insert(1,b1);
L.Insert(2,b2);
L.Insert(3,b3);
cout << "图书的数量为: " << L.GetLength() << endl;
Book b4 = L.GetElem(2);
cout << "第2本书的名字是:" << b4.name << endl;
L.Delete(2);
cout << "图书的数量为: " << L.GetLength() << endl;
cout << "和b3信息相同的图书的位置是:" << L.Find(b3) << endl;
L.Clear();
cout << "图书的数量为: " << L.GetLength() << endl;
return 0;
}
出力結果: