数据结构 - 简单的顺序表结构

来源:互联网 发布:上海模型店淘宝地址 编辑:程序博客网 时间:2024/04/28 13:54
编写一个程序exp2-1.cpp,实现顺序表的各种运算(假设顺序表的元素类型为char),并在此基础上完成如下功能:
(1)初始化顺序表L;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出顺序表L;
(4)输出顺序表L的长度;
(5)判断顺序表L是否为空;
(6)输出顺序表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出顺序表L;
(10)删除L的第3个元素;
(11)输出顺序表L;

(12)释放顺序表L。

#include <iostream>#include <cstdlib>#define MaxSize 50using namespace std;struct SqList{    char data[MaxSize];    int length;};void CreateList(SqList *&,char *,int);//向顺序表L插入数据void InitList(SqList *&);//初始化顺序表Lvoid DestroyList(SqList *);//销毁顺序表void DispList(SqList *);//输出顺序表Lint 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;}

运行结果:


0 0
原创粉丝点击