1.顺序表的定义和操作初始化
顺序表的结构体数据类型
typedef struct{
Elem *elem;//存储数据第一个元素的地址
int length;//顺序表的当前长度
}SqList;//定义结构体数据类型sqlist,用于表示顺序表
完整算法
void Initilist(Sqlist &L)
{
L.elem = new ElemType[MAXSIZE];
if(L.elem == NULL)
exit(OVERFLOW);
else
L.length = 0;
}
2.顺序表的查找操作
查找的两种情况:
1.根据给定元素的下标进行查找(通过数组下标进行定位)
2.根据给定的元素值进行查找
顺序表是通过一维数组来表示的
下标从0开始,只是为了方便后面算法的描述
已知一张顺序表,就知道表的长度
完整算法
int Locate_Sq(SqList L,ElemType e) {
i = 1;n = L.length;
while(i <= n && e != L.elem[i])
i++;
if(i <= n && e == L.elem[i])
return(i);
else
return(0);
}
3.顺序表的插入操作
操作实现
1.已知表中的长度
2.已知表中的每个元素
完整实现
int Insert_Sq(SqList &L,int i,Elemtype x)
{
if(i < 1 || i > L.length+1)
return ERROR;
if(L.length >= MAXSIZE-1)
return ERROR;
for(k = L.length;k >= i; k--)
L.elem[k+1] = L.elem[k];
L.elem[i] = k;
L.length++;
return OK;
}
4.顺序表的删除操作
具体实现:
Status Delete_Sq(SqList &L,int i;Elemtype &e)
{
if(i < 1 || i > L.length)
return ERROR;
e = L.elem[i];
for(k = i;k <= L.length - 1;k++)
L.elem[k] = L.elem[k+1];
L.Length--;
return OK;
}
5.集合的合并(用顺序表表示集合)
/**
* 集合的合并思路:
* 1.将la的元素拷贝到lc表中;
* 2.对lb中的元素逐个扫描
* 3.定位该元素不在la表中,则插入;
* 4.若插入成功则lc表长增加;
*
*/
void mergelist_sq(sqlist &a,sqlist &b,sqlist &c)
{
lc.length = la.length;
lc.len = la.length + lb.length + 1;
lc.elem = new ElemType[lc.len];
for(i = 1;i <= la.length; i++)
lc.elem[i] = la.elem[i];
for(j = 1; j <=lb.length;j++) {
k = locate(la,lb.elem[j]);
if(k == 0) {
lc.elem[lc.length+1] = lb.elem[j];
lc.length++;
}
}delete la,delete lb;
}