#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;
}
C - 顺序线性表简单实现
最新推荐文章于 2021-05-21 15:10:21 发布