顺序表的运算

#include <iostream>
#include <cstdio>
#include <cstdlib>
#define MaxSize 50
using namespace std;
typedef struct
{
    char data[MaxSize];
    int length;
}SqList;

void InitList(SqList * &L)
{
    L=(SqList *)malloc(sizeof(SqList));
    L->length=0;
}
void DestroyList (SqList * &L)
{
    free(L);
}
bool ListEmpty(SqList * &L)
{
    return (L->length==0);
}
int ListLength(SqList * &L)
{
    return (L->length);
}
void DispList(SqList * &L)
{
    int i;
    for(i=0;i<L->length;i++)
    {
        cout<<L->data[i];

    }
    cout<<endl;
}
bool GetElem(SqList * &L,int i,char &e)
{
    if((i<1)||(i>L->length))
        return false;
    e=L->data[i-1];
    cout<<e<<'\n';
    return true;
}
int LocateElem(SqList * &L,char &e)
{
    int i=0;
    while(i<L->length&&L->data[i]!=e)
        i++;
    if(i>L->length)
        return 0;
    else
        return i+1;
}
bool ListInsert(SqList * &L,int i,char &e)
{
    int j;
    if(i<1||i>L->length+1)
        return false;
    i--;
    for(j=L->length;j>i;j--)
        L->data[j]=L->data[j-1];
    L->data[i]=e;
    L->length++;
    return true;
}
void wc(SqList * &L,char a[])
{
    int j;
    for(j=0;a[j]!='\0';j++)
    {
        L->data[j]=a[j];
        L->length++;
    }
}
bool ListDelete(SqList * &L,int i,char &e)
{
    int j;
    if(i<1||i>L->length)
        return false;
    i--;
    e=L->data[i];
    for(j=i;j<L->length-1;j++)
        L->data[j]=L->data[j+1];
    L->length--;
    return true;
}
int main()
{
    SqList *L;
    InitList(L);
    cout<<"初始化顺序表L"<<endl;
    char a[6];
    cout<<"采用尾插法一次插入元素:";
    gets(a);
    wc(L,a);
    cout<<"输出顺序表:";
    DispList(L);
    cout<<"顺序表的长度为:"<<ListLength(L)<<'\n';
    if(ListEmpty(L)==0)
        cout<<"顺序列表不为空!"<<'\n';
    else
        cout<<"顺序列表为空!"<<'\n';
    char e,ch,sh;
    int i,m,x;
    cout<<"查找第i个元素,请输入i:";
    cin>>i;
    cout<<"输出顺序表的第"<<i<<"个元素= ";
    GetElem(L,3,e);
    cout<<"查找ch元素的位置,请输入ch:";
    cin>>ch;
    cout<<"输出元素"<<ch<<"的位置:"<<LocateElem(L,ch)<<'\n';
    cout<<"在第m个位置上插入元素sh,请输入m和sh: ";
    cin>>m>>sh;
    ListInsert(L,m,sh);
    cout<<"在顺序表第"<<m<<"个位置上插入元素"<<sh<<"后,输出顺序表:";
    DispList(L);
    cout<<"删除顺序表第x个元素,请输入x:";
    cin>>x;
    ListDelete(L,x,e);//还是同上
    cout<<"删除顺序表第"<<x<<"个元素后,输出顺序表:";
    DispList(L);
    DestroyList(L);//同上
    cout<<"释放顺序表L!";
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值