2.1 顺序表
初始化
顺序表初始化分为两种方式:有初始值和没有初始值,前者通过参数将数组元素赋值到顺序表,后者创建空的顺序表。
Sq_List()
{
elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!elem)
exit(OVERFLOW);
length = 0;
listsize = LIST_INIT_SIZE;
};
创建有初始值的顺序表时,数据的赋值可以通过运算符函数[]或者指针进行复制,下面代码使用了两种赋值方法。
Sq_List(ElemType a[], int n)
{
// []
// elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
// if(!elem) exit(OVERFLOW);
// for(int i = 0; i < n; i++){
// elem[i] = a[i];
// }
// length = n;
// listsize = LIST_INIT_SIZE;
// 指针
elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!elem)
exit(OVERFLOW);
ElemType *end = a + n - 1;
ElemType *p = elem;
ElemType *q = a;
while (q <= end)
{
*p++ = *q++;
}
length = n;
listsize = LIST_INIT_SIZE;
}
插入数据
顺序表的插入较为麻烦,时间复杂度为O(n),需要将插入位置和该位置后边的数据向后移动一位,因此时间复杂度为O(n),数据后移的方式同样可以通过运算符[]和指针来进行操作,下面介绍了两种方法。
Status InsertList(ElemType x, int i){
if(i<1||i>(length+1)) return ERROR; // 判断插入位置是否合法
if(length >= listsize){
ElemType* newbase = (ElemType *)realloc(elem, (listsize + LISTINCREMENT) * sizeof(ElemType));
elem = newbase;
listsize += LISTINCREMENT;
} // 判断数组空间是否充足
// // []后移
// for(int j = length; j >= i; j--){
// elem[j] = elem[j - 1];
// }
// elem[i - 1] = x;
// length += 1;
// return OK;
// 指针后移
ElemType* p = elem + length;
ElemType* end = elem + i;
while(p>=end){
*p = *(p - 1);
p--;
}
*p = x;
length++;
return OK;
}
删除数据
顺序表中数据删除和数据插入很类似,都需要将后边的数据移动。数据删除需要将插入位置后边的数据全部向前移动一位,可以通过运算符[]和指针来进行操作,下面介绍了两种方法。
Status DeleteList(int i){
if(i<1||(i>length)) return ERROR;
// // []
// for(int j = i - 1; j < length - 1; j++){
// elem[j] = elem[j + 1];
// }
// length -= 1;
// return OK;
// *
ElemType* end = elem + length - 1;
ElemType* q = elem + i - 1;
while(q<=end){
*q = *(q + 1);
q++;
}
length--;
return OK;
}
清空顺序表
顺序表中清空顺序表可以不对数据进行删除,在class中定义了length数据,记录顺序表中数据的长度,即使数据不删除,只要length的值赋值为0,就实现了数据清空的目的,但实际物理地址仍存储着数据,但是无法直接调用。
Status ClearList(){
length = 0;
return OK;
}
顺序表反转
顺序表反转即将数据方向存储,可以通过以下两个方法进行实现。
- 将length对半分开,实现两端元素的交换;
- 创建一个新的顺序表,将原来顺序表的元素反向赋值给新的顺序表,最后将新的顺序表首地址赋值给elem;
Status TraverseList(){
ElemType *newbase = (ElemType *)malloc(listsize * sizeof(ElemType));
if(!newbase) return ERROR;
// // []
// for(int i = 0; i < length; i++){
// newbase[i] = elem[length - i - 1];
// }
// free(elem);
// elem = newbase;
// return OK;
// *
ElemType* q = newbase;
ElemType* p = elem + length - 1;
ElemType* end = elem;
while(p>=end){
*q ++ = *p --;
}
free(elem);
elem = newbase;
return OK;
}