(12)释放顺序表L。
#include <iostream> #include <cstdlib> #define MaxSize 50 using namespace std; struct SqList { char data[MaxSize]; int length; }; void CreateList(SqList *&,char *,int);//向顺序表L插入数据 void InitList(SqList *&);//初始化顺序表L void DestroyList(SqList *);//销毁顺序表 void DispList(SqList *);//输出顺序表L int ListLength(SqList *);//、、返回顺序表的长度 bool ListEmpty(SqList *);//、、判断顺序表是否为空 char GetElem(SqList *,int);//、、求顺序表某一个元素的值 int LocateElem(SqList *,char);//输出某一个元素的位置 bool ListInsert(SqList *&,int,char);//在某个元素位置上插入元素 bool ListDelete(SqList *&,int);//删除某一个元素 int main() { char s[]="abcde"; SqList *L; InitList(L); cout<<"(1)初始化顺序表L"<<endl; CreateList(L,s,5); cout<<"(2)依次采用尾插法插入a,b,c,d,e元素"<<endl; cout<<"(3)输出顺序表L:"; DispList(L); cout<<"(4)顺序表L长度="<<ListLength(L)<<endl; cout<<"(5)顺序表L为"<<(ListEmpty(L)?"":"非")<<"空"<<endl; cout<<"(6)顺序表L的第3个元素="<<GetElem(L,3)<<endl; cout<<"(7)元素a的位置="<<LocateElem(L,'a')<<endl; cout<<"(8)在第4个元素位置上插入f元素"<<(ListInsert(L ,4,'f')?"...Success":"...Failed")<<endl; cout<<"(9)输出顺序表L:"; DispList(L); cout<<"(10)删除顺序表L的第3个元素"<<(ListDelete(L,3)?"...Success":"...Failed")<<endl; cout<<"(11)输出顺序表L:"; DispList(L); cout<<"(12)释放顺序表L"; DestroyList(L); } void InitList(SqList *&L) { L=(SqList *)malloc(sizeof(SqList)); L->length=0; } void CreateList(SqList *&L,char *a,int n) { int i; L=(SqList *)malloc(sizeof(SqList)); for (i=0;i<n;i++) L->data[i]=a[i]; L->length=n; } void DispList(SqList *L) { int i; for(i=0;i<L->length;i++) cout<<L->data[i]<<" "; cout<<endl; } void DestroyList(SqList *L) { free(L); } int ListLength(SqList *L) { return L->length; } bool ListEmpty(SqList *L) { return(L->length==0); } char GetElem(SqList *L,int n) { return L->data[n-1]; } int LocateElem(SqList *L,char s) { int i=0; while (i<L->length && L->data[i]!=s) i++; if (i>L->length) return 0; else return i+1; } bool ListInsert(SqList *&L,int n,char s) { int j; if (n<1 || n>L->length+1) return false; n--; for(j=L->length;j>n;j--) L->data[j]=L->data[j-1]; L->data[n]=s; L->length++; return true; } bool ListDelete(SqList *&L,int n) { int j; if (n<1 || n>L->length+1) return false; n--; for(j=n;j<L->length-1;j++) L->data[j]=L->data[j+1]; L->length--; return true; }
运行结果: