线性表的顺序实现

本文探讨了线性表的两种顺序实现方式,包括使用一层指针和两层指针的方法,详细解析了每种实现的原理和应用场景。
摘要由CSDN通过智能技术生成

使用一层指针

//
// Created by andyi on 2020/11/8.
//
# include "stdio.h"
# include <stdlib.h>
# define LIST_INIT_SIZE 10
# define LISTINCREMENT 10
# define ELEM int
typedef struct {
   
    ELEM* head;
    int length;
    int listsize;
}SqList;
// 初始化
SqList* InitList_Sq(SqList* L) {
   
    //    static SqList* L;
    //    static SqList l;
    L = (SqList*)malloc(sizeof(SqList));
    L->head = (ELEM*)malloc(LIST_INIT_SIZE * sizeof(ELEM));
    //    L = &l;
    if (!L->head) {
   
        printf("failed------");
        exit(0);
    };
    L->length = 0;
    L->listsize = LIST_INIT_SIZE;
    return L;
} // InitList_Sq
// 求长度
int ListLength(SqList* L) {
   
    return L->length;
}
// 打印每一个元素
void ListTraverse(SqList* L) {
   
    int len = ListLength(L);
    for (int k = 0;k < len; k++) {
   
        printf("%d ", L->head[k]);
    }
}
// 返回每一个第i个元素
ELEM getElem(SqList* L, int i) {
   
    return L->head[i];
}
// 在第i个位置插入e
void ListInsert(SqList* L, int index, ELEM e) {
   
    if (index > L->length || index < 0) {
   
        printf("there is an error -----");
        return;
    }
    else {
   
        if (L->length >= L->listsize) {
   
            L->head = (ELEM*)realloc(L->head, (L->length + LISTINCREMENT) * sizeof(ELEM));
            if (!L->head) {
   
                printf("realloc failed\n");
                return;
            }
            L->listsize += LISTINCREMENT;
        }
        for (int i = L->length; i > index; i--) {
   
            L->head[i] = L->head[i - 1];
        }
        L->head[index] = e;
        L->length++;
        return;
    }
}
//重置列表
SqList* ClearList(SqList* L) {
   
    L->length = 0;
    L->head = (ELEM*)realloc(L->head, LIST_INIT_SIZE * sizeof(ELEM));
    L->listsize = LIST_INIT_SIZE;
    return L;
}
// 销毁列表
void DestoryList(SqList* l) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值