数据结构之顺序表操作

/*
编写一个程序,实现顺序表的各种基本运算(假设顺序表的元素类型为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 <malloc.h>
#include <cstdio>
#include <cstring>
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int length;
} SqList;

void InitList(SqList *&L)  //初始化顺序表L
{
    L=(SqList *)malloc(sizeof (SqList));
    L->length=0;
}

void ListInsert(SqList *&L,ElemType a[],int n)   //采用尾插法依次插入元素a,b,c,d,e
{
    for(int i=0; i<n; i++)
        L->data[i]=a[i];
    L->length=n;
}
void DispList(SqList *L)         //输出顺序表L
{
    for(int i=0; i<L->length; i++)
        cout<<L->data[i]<<" ";
    cout<<endl;
}
int ListLength(SqList *L)      //输出顺序表L的长度
{
    return(L->length);
}
bool ListEmpty(SqList *L)      //判断顺序表L是否为空
{
    return(L->length==0);
}
void GetElem(SqList *L,int j)    //输出顺序表的第i个元素
{
    for(int i=0; i<L->length; i++)
    {
        if(i==(j-1))
            cout<<L->data[i]<<endl;
    }
}
void Displocation(SqList *L,ElemType a)  //输出元素a的位置
{
    for(int i=0; i<L->length; i++)
    {
        if(L->data[i]==a)
            cout<<i+1<<" ";
    }
    cout<<endl;
}
bool ListInsert(SqList *&L,int i,ElemType 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;
}
bool ListDelete(SqList *&L,int i)    //删除数据元素
{
    int j;
    if(i<1||i>L->length+1)
        return false;
    i--;
    for(j=i; j<L->length; j++)
        L->data[j]=L->data[j+1];
    L->length--;
    return true;
}
void DestoryList(SqList *&L)        //销毁顺序表
{
    free(L);
}
int main()
{
    char a[10];
    char b='a';
    gets(a);
    SqList *L;
    InitList(L);
    ListInsert(L,a,strlen(a));
    cout<<"输出顺序表:";
    DispList(L);
    cout<<"顺序表的长度:"<<ListLength(L)<<endl;
    cout<<"顺序表是否为空:";
    if(ListEmpty(L))
        cout<<"是"<<endl;
    else
        cout<<"否"<<endl;
    cout<<"顺序表L的第三个元素为:";
    GetElem(L,3);
    cout<<"输出元素"<<b<<"的位置:";
    Displocation(L,b);
    ListInsert(L,4,'f');
    cout<<"已在第4个元素位置上插入元素f"<<endl;
    cout<<"输出顺序表:";
    DispList(L);
    ListDelete(L,3);
    cout<<"已删除第3个位置上的元素"<<endl;
    cout<<"输出顺序表:";
    DispList(L);
    DestoryList(L);
    cout<<"顺序表已释放!"<<endl;
    return 0;
}


 

运行结果:


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值