顺序存储结构线性表的各项操作

#include #define MAXSIZE 20 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0using namespace std; typedef int ElemType; typedef int Status; typedef struct { ElemType data[MAXSIZE]; int length; }SqList; //顺序表L已存在,用e返回L中第i个数据元素的值 Status GetElem(SqList L, int i, ElemType *e) { if (L.length == 0 || i<1 || i>L.length) return ERROR; *e = L.data[i - 1]; return OK; }//顺序表L已存在,在L中第i个位置之前插入新的数据元素e,L的长度加1 Status ListInsert(SqList *L, int i, ElemType e) { int k; if (L->length == MAXSIZE) return ERROR; if (i<1 || i>L->length + 1) return ERROR; if (i <= L->length) { //若插入数据位置不在表尾 for (k = L->length - 1; k >= i - 1; --k) L->data[k + 1] = L->data[k]; } L->data[i - 1] = e; ++L->length; return OK; }//顺序表L已存在,删除L中第i个数据元素,并用e返回其值,L的长度减1 Status ListDelete(SqList *L, int i, ElemType *e) { int k; if (L->length == 0) return ERROR; if (i<1 || i>L->length) return ERROR; *e = L->data[i - 1]; if (i < L->length) {//将删除位置后继元素前移 for (k = i; k < L->length; ++k) L->data[k - 1] = L->data[k]; } --L->length; return OK; }int main() { SqList L = { {0,1,2,3,4,5,6,7,8,9 }, 10}; ElemType a,e; ListInsert(&L, 2, 11); ListDelete(&L, 1, &a); GetElem(L, 1, &e); cout << e << endl; }

    推荐阅读