数据结构 顺序表之增删改查

初识数据结构之顺序表,上说话👇。

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

typedef struct
{
    int data[maxSize];  //存放数据
    int length;     //数组长度
}SqList;  //构建一个结构体

void printList(SqList L)  //打印数组
{
    cout << "the list is:";
    for(int i=0;i<L.length;i++)
        cout << L.data[i] << " ";
    cout << endl;
}

void addElem(SqList &L, int location, int elem) //在location位置添加元素elem
{
    if(location<1 || location>L.length)
        cout << "Error:out of range!";
    else
    {
        for(int i=L.length-1;i>=location-1;i--)
            L.data[i+1] = L.data[i];
        L.data[location-1] = elem;
        L.length++;
    }

}
void deleteElem(SqList &L, int location)  //删除location位置的元素
{
    if(location<1 || location>L.length)
        cout << "Error:out of range!";
    else
    {
        for(int i=location-1;i<L.length-1;i++)
            L.data[i] = L.data[i+1];
        L.length--;
    }
}

void changeElem(SqList &L, int location, int elem)  //更改location处的元素 into elem
{
    if(location<1 || location>L.length)
        cout << "Error:out of range!";
    else
        L.data[location-1] = elem;
}

void searchElem(SqList L, int elem)   //在数组中查询elem元素是否存在
{
    int cnt = 0;
    for(int i=0; i<L.length;i++)
    {
        if(L.data[i] == elem)
        {
            cout <<"The location of " <<
            elem << " is " << i+1 << endl;
            cnt++;
            break;
        }
    }
    if(cnt == 0)
        cout << "Not found!";
}

int main()
{
    SqList L;

    //初始化SqList
    int n;
    cout << "enter the number of your list:";
    cin >> n;
    L.length = n;
    for(int i=0;i<L.length;i++)  //这里是初始化顺序表,为了方便用for循环赋值
        L.data[i] = i+1;

    //输出SqList
    printList(L);

    cout << "Add 0 in SqList at the location of 3" << endl;
    addElem(L, 3, 0);
    cout << "After added, the SqList's length is " << L.length << endl;
    printList(L);
    cout << endl;

    cout << "Delete the element at the location of 3 in SqList" << endl;
    deleteElem(L, 3);
    cout << "After deleted, the SqList's length is " << L.length << endl;
    printList(L);
    cout << endl;

    cout << "Change the element at the location of 2 in SqList into 0" << endl;
    changeElem(L,2,0);
    cout << "After changed, the SqList's length is " << L.length << endl;
    printList(L);
    cout << endl;

    cout << "Search 5 in SqList" << endl;
    searchElem(L,5);
    cout << "After searched, the SqList's length is " << L.length << endl;
    printList(L);
    cout << endl;
}

运行如图
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值