C - 顺序线性表简单实现

#include<stdio.h>
#include<stdlib.h>

#define DEFAULT_SIZE 1

typedef struct {
    int * data;
    int length;
    int max_size;
}seqList;

//初始化线性表
void init_list(seqList *list);
//添加一个元素到尾部
int add_to_tail(seqList *list,int el);
//打印线性表所有元素
void print_list(seqList *list);
//扩容,每次扩大一倍
int incre_size(seqList *list);
//获取在Index位置的元素,从0开始
int get(seqList *list,int index);
//删除在Index位置的元素,从0开始
int del(seqList *list,int index);
//销毁线性表
void destory(seqList *list);
//清空线性表
void clear_list(seqList *list);

int main(){

    //声明线性表
    seqList list;

    init_list(&list);

    add_to_tail(&list,1);
    add_to_tail(&list,2);

    print_list(&list);

    printf("%d \n",get(&list,3));

    printf("%d \n",get(&list,1));

    del(&list,1);

    print_list(&list);

    destory(&list);

    print_list(&list);

    return 0;
}

void init_list(seqList *list){
    list->data = (int *)malloc(sizeof(int)*DEFAULT_SIZE);
    list->max_size = DEFAULT_SIZE;
    list->length = 0;
}

int add_to_tail(seqList *list,int el){
    if(list->length == DEFAULT_SIZE){
        if(!incre_size(list)){
            return 0;
        }
    }
    list->data[list->length] = el;
    list->length ++;
    return 1;
}

void print_list(seqList *list){
    printf("[");
    for(int i = 0; i < list->length; i++){
        printf("%d",list->data[i]);
        if(i<list->length - 1){
            printf(",");
        }
    }
    printf("]\n");

}

int incre_size(seqList *list){
    int *data = list->data;
    list->data = (int *)malloc(sizeof(int)*list->length*2);
    if(!list->data){
        return 0;
    }
    for(int i = 0; i < list->length; i++){
        list->data[i] = data[i];
    }
    free(data);
    list->max_size = list->length;
    return 1;
}

int get(seqList *list,int index){
    if(index <0 || index >= list->length){
        printf("index out of range!\n");
        return 0;
    }
    return list->data[index];
}

int del(seqList *list,int index){
    if(index <0 || index >= list->length){
        printf("index out of range!\n");
        return 0;
    }
    for(int i = index; i < list->length - 1;i++){
        list->data[i] = list->data[i+1];
    }
    list->length--;
    return 1;
}

void destory(seqList *list){
    free(list);
}

void clear_list(seqList *list){
    list->length = 0;
    list->max_size = DEFAULT_SIZE;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值