数据结构与算法 01 线性表的顺序存储结构

本文详细介绍了使用小甲鱼的《数据结构和算法》进行学习的经验,包括代码实现、数据结构创建、元素操作等核心知识点。通过实例展示了如何在`main.c`文件中创建和操作数据结构,提供了深入理解数据结构与算法的实践指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正在学习数据结构与算法,学习资料是小甲鱼的《数据结构和算法》,记录日志

main.c

#include "data.h"
#include <stdio.h>

int main() {
    ElemType i[9];
    ElemType k[9];

    ElemType* m;
    ElemType* n;

    ElemType* e = (ElemType *)malloc(sizeof(ElemType));

    SqList* L = CreateSqList();

    m = &i;
    n = &k;

    int j;
    for(j = 1; j < 10; j++) {
        i[j-1] = j;
        k[j-1] = j;
        InsertElem(L,j,m);
        InsertElem(L,j,n);
        m++;
        n++;
    }

    DeleteElem(L, 15, e);
    printf("%d\n",*e);

    GetElem(L, 10, e);
    printf("%d\n",*e);

    for(j = 0; j < L->length; j++) {
        printf("%d\n", L->data[j]);
        printf("%d\n", *L->data[j]);
    }

    return 0;
}


data.h

#define MAXSIZE 20

#define OK 1;
#define ERROR 0;
#define TRUE 1;
#define FALSE 0;

typedef int ElemType;
typedef struct {
    ElemType* data[MAXSIZE];
    int length;
} SqList;

typedef int Status;

SqList* CreateSqList(void);
Status GetElem(SqList* L, int i, ElemType* e);
Status InsertElem(SqList* L, int i, ElemType* e);
Status DeleteElem(SqList* L, int i, ElemType* e);

data.c

#include "data.h"
#include <stdlib.h>

SqList* CreateSqList(void) {
    SqList *L;
    L = (SqList *)malloc(sizeof(SqList));
    L->length = 0;

    return L;
}

Status GetElem(SqList* L, int i, ElemType* e) {
    if(L->length == 0 || i < 1 || i > L->length) {
        return ERROR;
    }
    *e = *L->data[i-1];

    return OK;
}

Status InsertElem(SqList* L, int i, ElemType* e) {
    if(L->length == MAXSIZE) {
        return ERROR;
    }
    if(i<1 || i> L->length + 1) {
        return ERROR;
    }
    if(i-1 <= L->length) {
        int k;
        for(k = L->length; k >= i; k--) {
            L->data[k] = L->data[k-1];
        }
        L->data[i-1] = e;
        L->length++;
    }

    return OK;
}

Status DeleteElem(SqList* L, int i, ElemType* e) {
    if(i<1 || i>L->length) {
        return ERROR;
    }
    if(i <= L->length) {
        int k;
        *e = *L->data[i-1];
        for(k = i-1; k<L->length; k++) {
            L->data[k] = L->data[k+1];
        }
        L->data[L->length - 1] = NULL;
        L->length--;
    }

    return OK;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值