线性表的顺序结构,C语言实现
#include <stdio.h>
#include <stdlib.h>
#define LISTSIZE_INIT 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 50 //线性表存储空间的分配增量
typedef int ElemType; //数据元素的类型,int型
/*定义线性表*/
typedef struct {
ElemType *elem; //存储空间的基地址
int length; //当前线性表的长度
int size; //当前分配的存储容量
}SqList;
/*初始化*/
int InitList(SqList *list) {
// 开辟第一个存储空间
ElemType *elem = (ElemType *)malloc(LISTSIZE_INIT * sizeof(ElemType));
// 判断空间是否分配成功
if (!list->elem) {
return -1;
}
// 将第一个存储空间的地址(基地址)赋值给elem
list->elem = elem;
// 当前长度
list->length = 0;
// 当前分配量
list->size = LISTSIZE_INIT;
return 0;
}
/*插入元素,按照下标插入,下标从0~n*/
int ListInsert(SqList *list ,int index, ElemType elem) {
// 判断是否越界
if (index < 0 || index > list->length) {
return -1;
}
// 判断存储空间是否够用
if (list->length >= list->size) {
ElemType *newElem = (ElemType *)realloc(list->elem, (list->size + LISTINCREMENT) * sizeof(ElemType));
if (!newElem) return -1; //存储空间分配失败
list->elem = newElem; //新基址
list->size += LISTINCREMENT;//增加存储容量
}
// 插入操作
ElemType *q,*p = NULL; //定义2个指针变量
q = &(list->elem[index]); //取出当前线性表下标为index的数据
// 从线性表最后一个元素开始,指针后移
for (p = (&(list->elem[list->length-1])); p >= q; --p) {
*(p+1) = *p;
}
// 将插入的元素放到原来q的位置上,即插入一个新的指针。
*q = elem;
// 线性表长+1。
++list->length;
return 0;
}
/*删除元素,按照下标删除,下标从0~n*/
int ListDelete(SqList *list,int index) {
if (index < 0 || index > list->length-1) {
return -1;
}
// 删除操作
ElemType *q, *p = NULL;
q = &(list->elem[index]); // 取出当前要删除的元素
p = &(list->elem[list->length-1]); // 线性表最后一个元素
for (; p >= q; ++q) {
*q = *(q+1);
}
--list->length; //表长-1
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
// 初始化一个线性表
SqList list;
InitList(&list);
printf("插入操作 \n");
// 插入元素
for (int i = 0; i < 10; i++)
{
if (ListInsert(&list, i, i) == 0) {
printf("%d \n", list.elem[i]);
}
}
printf("删除操作 \n");
// 删除元素
if (ListDelete(&list, 8) == 0) {
// 遍历线性表
for (int i = 0; i < list.length-1; i++) {
printf("%d \n", list.elem[i]);
}
} else {
printf("delete failed \n");
}
printf("表长:%d \n",list.length);
return 0;
}
有一个问题:关于删除操作,会不会造成内存泄露的问题?或者其他内存问题呢?