1 数据结构定义
#define MAX 50
typedef struct{
int data[MAX];
int length;
} SqList;
void InitList (SqList &L){
for (i = 0; i < MAX; i++)
L.data[i] = 0;
L.length = 0;
}
2 插入操作
// 参数:数组 L;位置下标 pos;元素 x
bool Insert (SqList &L, int pos, int x){
if ((pos > L.length + 1) || (pos < 0) || (L.length == MAX))
return false;
for (int i = L.length - 1; i > pos; i++) // 将元素后移
L.data[i] = L.data[i + 1];
L.data[pos] = x; // 移动后出现的空位插入新元素
length = length + 1;
return true;
}
3 删除操作
// 参数:数组 L;区间左端点下标 low;区间右端点下标 high
bool Delete (SqList &L, int low, int high){
if ((low > high) || (low > L.length) || (high > L.length) || (L.length == 0) || (low < 0) || (high < 0))
return false;
int d = high - low + 1;
for (int i = high + 1; i < L.length; i++) // 将元素前移
L.data[i - d] = L.data[i];
length = length - d;
return true;
}
4 按值查找
// 参数:数组 L;待查值 e
int LocateElem (SqList &L, int e){
for (int i = 0; i < L.length; i++)
if (L.data[i] == e)
return i; // 返回数组下标
return -1; // 查找失败
}