一、实验要求
二、实验代码
# include "bits/stdc++.h"
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100 //定义顺序表的最大长度
//定义数据结构体
typedef struct book
{
int number; //编号
string name; //名称
float price; //定价
}book;
//定义顺序表结构体
typedef struct
{
book data[MAXSIZE]; //顺序表数据
int length; //顺序表长度
}SqlList;
//顺序表的初始化函数
bool InitList_Sq(SqlList &L)
{
for (int i = 0; i < MAXSIZE; i++)
{
L.data[i].number = 0;
L.data[i].name = 'a';
L.data[i].price = 0;
}
L.length = 0;
SqlList *elem = &L;
if(elem != NULL)
return OK;
else
return ERROR;
}
//顺序表的插入操作
bool ListInsert_Sq(SqlList &L, int que, book num)
{
//判断插入的位置是否合法
if(que<0 || que>L.length)
return ERROR;
if(L.length >= MAXSIZE)
return ERROR;
for (int i = L.length; i > que; i--)
{
L.data[i] = L.data[i-1];
}
//添加新元素
L.data[que].number = num.number;
L.data[que].name = num.name;
L.data[que].price = num.price;
L.length ++;
return true;
}
//顺序表的打印输出操作
void Printout_Sq(SqlList &L)
{
cout << "编号" << setw(15) << "书名" << setw(15) << "定价" << endl;
for (int i = 0; i < L.length; i++)
{
cout << L.data[i].number << setw(15) << L.data[i].name << setw(15) << L.data[i].price << endl;
}
cout<<endl;
}
//顺序表的取出(按位置取出)
bool GetElem(SqlList &L, int i)
{
//判断查询的位置是否合理
if(i<0 || i>=L.length)
return ERROR;
cout << "第" << i << "条的图书信息为: " << endl;
cout << L.data[i].number << setw(15) << L.data[i].name << setw(15) << L.data[i].price << endl;
}
//顺序表的查找
int LocateElem_Sq(SqlList &L, float price)
{
for (int i = 0; i < L.length; i++)
{
if(L.data[i].price == price)
{
cout << "查找成功" << endl;
cout << "该价格对应的书名为: " << L.data[i].name << endl;
return 0;
}
}
cout << "查询失败" << endl;
return 0;
}
//顺序表的删除
bool ListDelete_Sq(SqlList &L, int que)
{
if(que<0 || que>=L.length)
return ERROR;
for (int i = que; i < L.length; i++)
{
L.data[i].number = L.data[i+1].number;
L.data[i].price = L.data[i+1].price;
L.data[i].name = L.data[i+1].name;
}
L.length --;
return OK;
}
int main()
{
setlocale(LC_ALL,"zh-CN"); //设置程序为中文编码
//========第一问===========
SqlList L;
if(InitList_Sq(L))
cout << "成功建立顺序表!!!" << endl;
else
cout << "顺序表建立失败!!!" << endl;
//========第二问===========
for (int i = 0; i < 3; i++)
{
book book;
cin >> book.number; //编号
cin >> book.name; //书名
cin >> book.price; //定价
ListInsert_Sq(L, i, book);
}
Printout_Sq(L); //输出
//========第三问===========
cout << "请输入一个位置用来获取数据:" << endl;
for (int i = 0; i < 2; i++)
{
int num;
cin >> num;
GetElem(L, num);
}
//========第四问===========
cout << "请输入所查找的书本价格:" << endl;
float price_elect;
cin >> price_elect;
LocateElem_Sq(L, price_elect);
//========第五问===========
cout << "请输入所要删除的书籍的编号:";
int num_elect;
cin >> num_elect;
if(ListDelete_Sq(L, num_elect))
cout << "删除成功" << endl;
else
cout << "删除失败" << endl;
Printout_Sq(L); //输出
return 0;
}