顺序表的操作代码 c+写法

/*
 * @Description: 描述
 * @Version: 1.0
 * @Autor: Nanke_南柯
 * @Date: 2021-10-04 14:32:10
 * @LastEditors: Nanke_南柯
 * @LastEditTime: 2021-10-08 21:20:41
 */
#include <stdio.h>
#include <stdlib.h>

// Status 是函数类型 其值是函数结果状态代码
typedef int Status; //定义函数要返回什么类型
typedef int ElemType;

typedef struct
{
    int max;
    int length;
    ElemType *elem; //数组当中首原属的地址
} SqList;           //顺序表类型

// 初始化
Status init(SqList &L, int MAXSIZE)
{
    L.max = MAXSIZE;
    L.length = 0;
    L.elem = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE); //为顺序表动态分配存储空间
    if (!L.elem)
        return false; //如果分配失败了
    return true;
}

// 插入
Status insert(SqList &L, int i, ElemType e)
{
    //判断传入下标是否小于0 或 大于数组长度-1
    if (i < 0 || i > L.max - 1)
        return false;
    if (L.max == L.length)
        return false;
    for (int j = L.length - 1; j >= i - 1; j--)
    {
        L.elem[j + 1] = L.elem[j]; //元素后移
    }
    L.elem[i] = e; //将新元素放入第i个位置
    L.length++;    //表长+1
    return true;
}

// 删除
Status deletes(SqList &L, int i)
{
    if (i < 0 || i > L.max)
        return false;
    for (int j = i; j <= L.length + 1; j++)
    {
        L.elem[j - 1] = L.elem[j]; //被删除元素之后的元素前移
    }
    L.length--; //表长-1
    return true;
}

// 销毁
void destory(SqList &L)
{
    L.max = 0;
    L.length = 0;
    free(L.elem); //从内存中释放
}
// 清空
void clear(SqList &L)
{
    L.max = 0;
    L.length = 0;
}
// 获取长度
int getLength(SqList L)
{
    return (L.length);
}
// 是否为空
int isEmpty(SqList L)
{
    if (L.length == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

//取值
int getElem(SqList L, int i, ElemType &e)
{
    if (i < L.length || i > L.length)
        return false;
    e = L.elem[i - 1];
    return true;
}

// 输出
Status sc(SqList L)
{
    for (int i = 0; i <= L.length - 1; i++)
    {
        printf("%d ", L.elem[i]);
    }

    printf("\n");
    return true;
}

int main()
{
    SqList list;
    init(list, 2);
    insert(list, 0, 2);
    insert(list, 1, 3);
    // printf("%d\n", getLength(list));
    // printf("%d\n", isEmpty(list));
    // deletes(list,0);
    // printf("%d\n",list.length);
    sc(list);
    // clear(list);
    // destory(list);
    return 0;
}

 

上一篇:数据结构实验报告——两个有序线性表的归并算法


下一篇:数据结构