#include <iostream> #include <cstdlib> using namespace std; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define LIST_INIT_SIZE 10 //线性表存储的初始分配量 #define LIST_INCREMENT 2 //线性表存储空间的分配增量 typedef int ElemType; typedef int Status; struct SqList { ElemType *elem; int length; int listsize; //当前分配的储存容量 }; void InitList(SqList &L) { L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if(!L.elem) exit(OVERFLOW); L.length = 0; L.listsize = LIST_INIT_SIZE; //初始储存容量 } void DestroyList(SqList &L) { free(L.elem); L.elem = NULL; L.listsize = 0; } void ClearList(SqList &L) { L.length = 0; } bool ListEmpty(SqList L) { if(L.length == 0) return true; else return false; } int ListLength(SqList L) { return L.length; } Status GetElem(SqList L,int i, ElemType &e) { if(i < 1 || i > L.length) return ERROR; e = *(L.elem + i - 1); return OK; } int LocateElem(SqList L,ElemType e) { ElemType *p; int i = 1; p = L.elem; while(i <= L.length) { if((*p++) == e) break; ++i; } if(i <= L.length) return i; else return 0; } Status PriorElem(SqList L,ElemType cur_e,ElemType &pre_e) { int i = 2; ElemType *p = L.elem + 1; while(i <= L.length && (*p) != cur_e) { p++; i++; } if(i > L.length) return INFEASIBLE; else { pre_e = *(--p); return OK; } } Status NextElem(SqList L,ElemType cur_e,ElemType &next_e) { int i = 1; ElemType *p = L.elem; while(i < L.length ) { if( *p == cur_e) break; i++; p++; } if(i == L.length) return INFEASIBLE; else { next_e = *++p; return OK; } } Status ListInsert(SqList &L,int i,ElemType e) { ElemType *newbase,*q,*p; if(i < 1 || i > L.length + 1) return ERROR; if(L.length >= L.listsize)//储存空间已满,增加分配 { if(!(newbase = (ElemType *)realloc(L.elem,(L.listsize + LIST_INCREMENT) * sizeof(ElemType)))) exit(OVERFLOW); //储存分配失败 L.elem = newbase; L.listsize += LIST_INCREMENT; } q = L.elem + i -1; //q为被插入元素位置 for(p = L.elem + L.length - 1; p >= q; --p) *(p+1) = *p; *q = e; ++L.length; return OK; } Status ListDelete(SqList &L,int i,ElemType &e) { ElemType *p,*q; if(i < 1 || i > L.length) return ERROR; p = L.elem + i - 1; //p为被删除元素的位置 e = *p; q = L.elem + L.length - 1; //表尾元素的位置 for(++p; p <= q; ++p) *(p - 1) = *p; L.length--; return OK; } void ListTraverse(SqList L) { ElemType *p; int i; p = L.elem; for(i = 1;i <= L.length; i++){ cout<<(*p++)<<" "; } cout<<endl; } int main() { SqList L; InitList(L); for(int i = 1; i <= 10; i++) ListInsert(L,i,i); ListTraverse(L); return 0; }