线性表即链表,基本特点是除第一个元素无直接前驱,最后一个元素无直接后继之外,其他么个数据元素都有一个前驱和后继。是最基本且最常用的一种线性结构。
2.1线性表的定义和特点
由n(n>=0)个数据特性相同的元素否城的有限序列成为线性表,n为线性表长度,当n=0称空表。
举例:1.26个英文字母的字母表是一个线性表,数据元素是单个字母。
2.学生信息表中,每一个学生为一个数据元素,包括学号、姓名、性别等等数据项。
2.2案例:图书信息管理系统。
2.3线性表的类型定义
线性表是一个相当灵活的数据结构,其长度可根据需要增长或缩短,即对线性表的数据元素不仅可以进行插入和删除等操作。
线性表的抽象数据类型包括:1. 初始化2. 取值3. 查找4. 插入5. 删除
2.4线性表的顺序表示和实现
2.4.1线性表的顺序存储表示
线性表的顺序表示指的是用一组地址连续的存储单元一次存储线性表的数据元素。
这种存储结构的线性表为顺序表。其特点是,逻辑上香菱的数据元素,其物理次序也是相邻的。
其关系可用下图来表示
线性表是一种随机存储的存储结构,在高级语言中通常用数组表示,在C语言中可用动态分配的一维数组表示线性表。
顺序表的类型定义:
#define MAXSIZE 100 //最大长度
typedef struct {
ElemType *elem; //指向数据元素的基地址
int length; //线性表的当前长度 <span style="font-family: Arial, Helvetica, sans-serif;">}SqList;</span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">2.3.2顺序表中基本操作的实现</span>
实例:顺序表的基本操作
#include<iostream>
#include<fstream> //file
#include<string>
#include<iomanip> //io manipulator
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Statues;
typedef int ElemType;
#define MAXSIZE 100
struct Book {
string id; //ISBN
string name;
double price;
};
typedef struct {
Book *elem; //base address
int length;
} SqList;
//Init
Statues InitList_Sq(SqList &L) {
L.elem = new Book[MAXSIZE]; //Application memory space ★
if (!L.elem)
exit(OVERFLOW);
L.length = 0;
}
//Get
Statues GetElem(SqList L, int i, Book &e) {
if (i < 1 || i > L.length)
return OVERFLOW;
e = L.elem[i - 1];
return OK;
}
//Locate
Statues LocateElem_Sq(SqList L, double e) {
for (int i = 0; i < L.length; i++)
if (L.elem[i].price == e)
return i + 1;
return 0;
}
//Insert
Statues ListInsert_Sq(SqList &L, int i, Book e) {
if((i < 1) || (i > L.length+1))
return ERROR;
if (L.length == MAXSIZE)
return ERROR;
for (int j = L.length - 1; j >= i - 1; j--)
L.elem[j + 1] = L.elem[j];
L.elem[i - 1] = e;
++L.length;
return OK;
}
//Delete
Statues ListDelete_Sq(SqList &L, int i) {
if ((i<1) || (i>L.length))
return ERROR;
for (int j = i; j <= L.length; j++)
L.elem[j - 1] = L.elem[j];
--L.length;
return OK;
}
int main() {
SqList L;
int i = 0, temp, a, c, choose;
double price;
Book e;
string head_1, head_2, head_3;
cout << "1.建立\n";
cout << "2.输入\n";
cout << "3.取值\n";
cout << "4.查找\n";
cout << "5.插入\n";
cout << "6.删除\n";
cout << "7.输出\n";
cout << "8.写入\n";
cout << "0.退出\n";
choose = -1;
while (choose != 0) {
cout << "请选择:";
cin >> choose;
switch(choose) {
case 1:
if (InitList_Sq(L))
cout << "Create the List successful!\n\n";
else
cout << "Create the List failed.\n\n";
break;
case 2: { //scanf //涉及到文件操作 括号不能省
i = 0;
L.elem = new Book[MAXSIZE];
if (!L.elem)
exit(OVERFLOW);
L.length = 0;
fstream file;
file.open("book.txt");
if (!file) {
cout << "can not found the file." << endl;
exit(ERROR);
}
file >> head_1 >> head_2 >> head_3;
while(!file.eof()){
file >