线性表之顺序表操作
1. 动态数组的定义
typedef struct{
ElemType *elem;
int Length;
int ListSize;
}SqList;
2. 初始化
bool InitList(SqList &L, int listSize)
{
if(listSize > 0)
{
L.elem = (ElemType*) malloc( listSize * sizeof(ElemType) );
if(!L.elem)exit(OVERFLOW);
L.Length = 0;
L.ListSize = listSize;
return success;
}
L.elem = (ElemType*) malloc(DEFAULT_CAPACITY * sizeof(ElemType));
if(!L.elem)exit(OVERFLOW);
L.Length = 0;
L.ListSize = DEFAULT_CAPACITY;
return success;
}
3. 按照位置插入元素
bool ListInsert(SqList &L, int index, ElemType e)
{
if( index < 1 || index > L.Length + 1) return failed;
if(L.Length >= L.ListSize)
{
ElemType* newelem = (ElemType*) realloc( L.elem, (L.ListSize + LISTINCREMENT) * sizeof(ElemType) );
if(!newelem) return failed;
L.ListSize += LISTINCREMENT;
L.elem = newelem;
}
for(int i = L.Length - 1; i >= index - 1; i --)
L.elem[i + 1] = L.elem[i];
L.elem[index - 1] = e;
L.Length++;
return success;
}
4. 删除指定位置元素
bool ListRemove(SqList &L, int index)
{
if( index < 1 || index > L.Length ) return failed;
for(int i = index; i < L.Length; i ++)
L.elem[i - 1] = L.elem[i];
L.Length--;
return success;
}
5. 获取指定位置元素
bool GetElem(SqList &L, int index, ElemType &e)
{
if(index <= 0) return failed;
e = L.elem[index - 1];
return success;
}
6. 获取指定元素第一次出现的位置
int LocateElem(SqList &L, ElemType e)
{
for(int i = 0; i < L.Length; i++)
{
if(L.elem[i] == e)return i + 1;
}
return -1;
}
6. 合并两个有序的顺序表
void MergeList(SqList la, SqList lb, SqList &Lc)
{
Lc.Length = la.Length + lb.Length, Lc.ListSize = Lc.Length;
Lc.elem = (ElemType*) malloc(Lc.ListSize * sizeof(ElemType));
int i = 0, ia = 0, ib = 0;
while(ia < la.Length || ib < lb.Length)
{
if(la.elem[ia] <= lb.elem[ib])
{
Lc.elem[i++] = la.elem[ia++];
}else{
Lc.elem[i++] = lb.elem[ib++];
}
}
while(ia < la.Length)
{
Lc.elem[i++] = la.elem[ia++];
}
while(ib < lb.Length)
{
Lc.elem[i++] = lb.elem[ib++];
}
}