目录
1.线性表的类型定义
相当于一个数组

2.基本操作

3.线性表的存储结构

4.补充
1.元素类型说明
2.数组定义
3.c语言的内存动态分配
计算出所需的大小再将它的指针赋值给data
4.c++的动态存储分配

5.c++中的参数传递
引用类型作参数
使用引用后传进函数的就是a和b本身,并没有重新复制一份

6.顺序表基本操作的实现
1.线性表的初始化

代码示例:
cpp
typedef struct{
int *elem;
int length;
}sqlist;
bool init_sqlist(sqlist &l)
{
l.elem = new int[100];
if(!l.elem) exit(-2);
l.length = 0;
return 1;
}
2.销毁线性表,清空线性表
代码示例:
cpp
void destory_list(sqlist &l)
{
if(l.elem) delete l.elem;
}
void clear_list(sqlist &l)
{
l.length = 0;
}
3.求线性表长度,判断线性表是否为空

代码示例:
cpp
int getlength(sqlist &l)
{
return l.length;
}
bool isempty(sqlist &l)
{
if(l.length == 0) return 1;
else return 0;
}
4.顺序表的取值
代码示例:
cpp
int getelem(sqlist &l,int i,int &e)
{
if(i < 1 || i > l.length) return -1;
e = l.elem[i-1];
return 1;
}
5.顺序表的查找

代码示例:
cpp
int locateelem(sqlist & l,int e)
{
for(int i = 0; i < l.length; i++)
{
if(l.elem[i] == e) return i + 1;
}
return 0;
}
6.顺序表的插入

代码示例:
cpp
int insert(sqlist &l,int i,int e)
{
if(i < 1 || i > l.length + 1) return 0;
if(l.length == 100) return 0;
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 1;
}
7.顺序表的删除

代码示例:
cpp
int deletelist(sqlist &l,int i)
{
if(i < 1 || i > l.length) return 0;
for(int j = i; j <= l.length - 1; j++)
{
l.elem[j - 1] = l.elem[j];
}
l.length--;
return 1;
}
7.顺序表的操作算法分析


8.总的代码及示例
cpp
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int *elem;
int length;
}sqlist;
void init_sqlist(sqlist &l)
{
l.elem = new int[100];
l.length = 0;
}
void destory_list(sqlist &l)
{
if(l.elem) delete l.elem;
}
void clear_list(sqlist &l)
{
l.length = 0;
}
int getlength(sqlist &l)
{
return l.length;
}
bool isempty(sqlist &l)
{
if(l.length == 0) return 1;
else return 0;
}
int getelem(sqlist &l,int i,int &e)
{
if(i < 1 || i > l.length) return -1;
e = l.elem[i-1];
return 1;
}
int locateelem(sqlist & l,int e)
{
for(int i = 0; i < l.length; i++)
{
if(l.elem[i] == e) return i + 1;
}
return 0;
}
int insert(sqlist &l,int i,int e)
{
if(i < 1 || i > l.length + 1) return 0;
if(l.length == 100) return 0;
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 1;
}
bool deletelist(sqlist &l,int i)
{
if(i < 1 || i > l.length) return 0;
for(int j = i; j <= l.length - 1; j++)
{
l.elem[j - 1] = l.elem[j];
}
l.length--;
return 1;
}
int main()
{
sqlist l;
init_sqlist(l);
cout << getlength(l) << endl;
insert(l,1,1);
insert(l,2,10);
insert(l,3,100);
insert(l,4,1000);
insert(l,5,10000);
cout << locateelem(l,100) << endl;
cout << locateelem(l,10000) << endl;
cout << getlength(l) << endl;
deletelist(l,3);
cout << getlength(l) << endl;
return 0;
}