顺序表操作(C++)

顺序表操作(C++)(实验一):

#include <iostream>
#define MAXSIZE 100
using namespace std;

//顺序表的结构体
typedef struct SqList{
    int *elem;
    int length;
}Sqlist;

//顺序表的初始化
void InitList(Sqlist &L){
    L.elem = new int[MAXSIZE];
    L.length = 0;
}

//插入数据
void ListInsert(Sqlist &L, int loc, int e){
    if(loc<1 || loc>L.length+1 || L.length==MAXSIZE){
        cout<<"非法操作\n";
        return ;
    }

    else
    {
        for(int i=L.length-1; i>=loc-1; i--){
            L.elem[i+1] = L.elem[i];
        }
        L.elem[loc-1] = e;
        L.length++;
        return ;
    }
}

//查找
int LocateElem(Sqlist L, int elem){
    for(int i=0; i<L.length; i++){
        if(L.elem[i]==elem)
            return i+1;
    }
    return -1;

}

//删除某个元素
void ListDelete(Sqlist &L, int loc){
    if(loc<1 || loc>L.length ){
        cout<<"非法操作"<<endl;
        return ;
    }
    else{
        for(int i=loc; i<=L.length; i++){
            L.elem[i-1] = L.elem[i];
        }
        L.length--;
        return ;
    }
}
//判空
bool IsEmpty(Sqlist L){
    if(L.length==0)
        return true;
    else
        return false;
}

//清空
void CleanList(Sqlist &L){
    L.length = 0;
}

//返回顺序表长度
int ListLength(Sqlist L){
    return L.length;
}

//输出某位置元素的直接前驱
void PreElem(Sqlist L, int loc){
    if(loc<=1){
        cout<<"非法操作"<<endl;
        return ;
    }
    cout<<"直接前驱:"<<L.elem[loc-2]<<endl;;
    return ;
}

//输出某位置元素的直接后继
void NextElem(Sqlist L, int loc){
    if(loc>=L.length){
        cout<<"非法操作"<<endl;
        return ;
    }
    cout<<"直接后继:"<<L.elem[loc]<<endl;
    return ;
}

//打印顺序表
void PrintList(Sqlist L){
    for(int i=0; i<L.length; i++){
        cout<<L.elem[i]<<endl;
    }
}
int main()
{
    //创建一个顺序表
    Sqlist L;
    //初始化顺序表
    InitList(L);
    //插入数据
    ListInsert(L, 1, 1);
    ListInsert(L, 1, 2);
    ListInsert(L, 1, 3);
    ListInsert(L, 1, 4);
    ListInsert(L, 1, 5);
    ListInsert(L, 1, 6);
    ListInsert(L, 1, 7);
        //ListInsert(L, 9, 7);ListInsert(L, 0, 7);非法
    //查找元素
    int loc = LocateElem(L, 6);
    if(loc==-1){
        cout<<"该元素不存在"<<endl;
    }
    else
        cout<<"位置:"<<loc<<endl;
    //查找前驱
    PreElem(L, 0);
    //查找后继
    NextElem(L, 7);
    //删除某个元素
    //ListDelete(L, 1);
        //    ListDelete(L, 0);    ListDelete(L, 8);非法
    //打印顺序表
    PrintList(L);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值