网课笔记
//顺序表
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct {
ElemType *data;
int size;
int length;
} SqList;
bool InitList(SqList &L, int s) { //顺序表初始化
if (s <= 0)
return false;
L.data = new ElemType[s];
if (L.data == NULL)
return false;
L.size = s;
L.length = 0;
return true;
}
int ListLength(SqList &L) { //表长
return L.length;
}
int Locate(SqList &L, const ElemType &e) { //按值查找
for (int i = 0; i < L.length; i++)
if (L.data[i] == e)
return i + 1;
return false;
}
bool GetData(SqList &L, int i, ElemType &e) { //获得第i个元素
if (i >= 1 && i <= L.length) {
e = L.data[i - 1];
return true;
}
return false;
}
bool InsList(SqList &L, int i, ElemType e) { //在第i个元素前插入
if (i < 1 || i > L.length + 1)
return false;
if (L.length == L.size) {
ElemType *temp = new ElemType[2 * L.size];
if (temp == NULL)
return false;
for (int i = 0; i < L.length; i++)
temp[i] = L.data[i];
delete[] L.data;
L.data = temp;
L.size = L.size * 2;
}
for (int k = L.length - 1; k >= i - 1; k--)
L.data[k + 1] = L.data[k];
L.data[i - 1] = e;
return true;
}
bool DelList(SqList &L, int i) { //删除第i个元素
if (i >= 1 && i <= L.length) {
for (int k = i; k < L.length; k++)
L.data[k - 1] = L.data[k];
L.length--;
return true;
} else
return false;
}
void DestroyList(SqList &L) { //销毁顺序表
delete[] L.data;
L.data = NULL;
L.length = 0;
L.size = 0;
}
void ClearList(SqList &L) { //清空顺序表
L.length = 0;
}
bool EmptyList(SqList &L) { //判断顺序表是否为空
if (L.length == 0)
return true;
else
return false;
}
void DispList(SqList &L) { //遍历顺序表,输出所有元素
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";