以下是线性表顺序存储的一些基本操作:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
int OK = 1;
int ERROR = -1;
int OVERFLOW = -1;
typedef struct {
int *elem; //存储空间基址
int length; //当前长度
int listsize; //链表长度
}SqList;
int InitList_Sq(SqList &L) {
L.elem = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
if(!L.elem) exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
} //InitList Sq
int InsertInto_Sq(SqList &L, int location, int e) {
//i值是否合法
//存储空间是否满足
int *newbase;
if(location<1 || location > L.length+1) return ERROR;
if(L.length >= L.listsize) {
newbase = (int *)realloc(L.elem,LIST_INIT_SIZE+LISTINCREMENT*sizeof(int)); //新的存储空间分配失败
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
int *q,*p;
q = &L.elem[location-1];
for(p = &(L.elem[L.length-1]); p>=q; --p) { //从表尾开始移动
*(p+1) = *p;
}
*q = e;
++L.length;
return OK;
}//InsertList Sq
int Delete_Sq(SqList &L, int location) {
if(location<1 || location>L.length) return ERROR;
int *q,*p;
q = &(L.elem[location-1]);
p = L.elem + L.length-1;
for(++q; q <= p; ++q) { //不可以q<p,可以q<p+1
*(q-1) = *q;
}
--L.length;
return OK;
}//DeleteList Sq
int LocateElem_Sq(SqList &L, int e) {
int *q,*p;
q = &(L.elem[0]);
p = L.elem+L.length;
for(; q<p; ++q) {
if(*q==e) return 1;
}
return 0;
}
void MargeList_Sq(SqList La, SqList Lb, SqList &Lc) { //两个链表的合并
int *pa, *pa_last, *pb, *pb_last, *pc, *pc_last;
pa = La.elem;
pb = Lb.elem;
Lc.listsize = Lc.length = La.length + Lb.length;
pc = Lc.elem =(int *)malloc(Lc.listsize*sizeof(int));
if(!Lc.elem) exit(OVERFLOW);
pa_last = La.elem + La.length-1;
pb_last = Lb.elem + Lb.length-1;
while(pa <= pa_last || pb <= pb_last) {
if(*pa <= *pb) *pc++ = *pa++; //等价于等价于 *pc=*pa; pc++; pa++;
else *pc++ = *pb++;
}
while(pa <= pa_last) *pc++ = *pa++;
while(pb <= pb_last) *pc++ = *pb++;
}//MergeList_Sq
int main() {
SqList list;
InitList_Sq(list);
InsertInto_Sq(list, 1, 1);
InsertInto_Sq(list, 2, 3);
InsertInto_Sq(list, 3, 5);
InsertInto_Sq(list, 4, 7);
for(int i = 0; i<list.length ;i++) {
printf("%d\n", list.elem[i]);
}
printf("\n");
Delete_Sq(list, 1);
for(int i = 0; i<list.length ;i++) {
printf("%d\n", list.elem[i]);
}
printf("\n");
int a = LocateElem_Sq(list, 3);
printf("%d", a);
}