上一篇博客写了一个定长的顺序表,定长的顺序表存储时由于长度的限定,使用不是很方便,在定长顺序表的基础上进行优化,使用动态扩容函数实现动态顺序表。
使用malloc() 函数对存储数据区域进行动态分配,每次插入时,使用判满函数 IsFull() 进行检查,结果返回真时,调用扩容函数 Inc(),扩容函数使用realloc() 函数进行二倍扩容 。
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define INIT_SIZE 10
typedef struct DSqlist
{
int *data;//存储数据的内存
int usedsize; //有效数据的个数
int size;//总单元数
}DSqlist,*PDSeqlist;
void InitSeqlist(PDSeqlist Psq)
{
assert(Psq != NULL);
if(Psq == NULL)
{
return;
}
Psq->data = (int*)malloc(sizeof(int)*INIT_SIZE);
assert(Psq->data != NULL);
Psq->usedsize = 0;
Psq->size = INIT_SIZE;
}
static bool isFull(PDSeqlist Psq)
{
if( Psq->usedsize == Psq->size )
{
return true;
}
return false;
}
static void Inc(PDSeqlist Psq)
{
Psq->data =(int *)realloc(Psq->data,Psq->size*sizeof(int)*2);
Psq->size*=2;
}
bool Insert(PDSeqlist Psq,int pos,int val)
{
assert(Psq != NULL);
if(isFull(Psq))
{
Inc(Psq);
}
if(pos < 0 || pos >Psq->usedsize || isFull(Psq ))
{
return false;
}
for(int i = Psq->usedsize-1;i >= pos;i-- )//从最后一位开始移动数据,移动到pos位置为止
{
Psq->data[i+1] = Psq->data[i];
}
Psq->data[pos] = val;
Psq->usedsize ++;
return true;
}
int Search(PDSeqlist Psq,int pos,int key)
{
assert(Psq != NULL);
if(pos < 0 || pos >=Psq->usedsize )
{
return false;
}
for(int i = 0; i<Psq->usedsize ;i++)
{
if(Psq->data[i] == key)
{
return i;
}
}
return -1;
}
bool DeletePos(PDSeqlist Psq,int pos,int *rtv)
{
assert(Psq != NULL);
if(pos < 0 || pos >=Psq->usedsize )
{
return false;
}
if(rtv != NULL)
{
*rtv = Psq->data [pos];
}
for(int i = pos;i<Psq->usedsize -1;i++)
{
Psq->data[i] = Psq->data[i+1];
}
Psq->usedsize --;
return true;
}
bool Delete(PDSeqlist Psq,int pos,int key)
{
int index = Search(Psq, pos,key);
if(index == -1)
{
return false;
}
return DeletePos(Psq,index,NULL);
}
bool GetElem(PDSeqlist Psq,int pos,int *rtv)
{
if(pos <0 || pos > Psq->usedsize )
{
return false;
}
*rtv = Psq->data [pos];
return true;
}
int GetLength(PDSeqlist Psq)
{
return Psq->usedsize ;
}
void Clear(PDSeqlist Psq)
{
Psq->usedsize = 0;
Psq->size =0;
}
void Destroy(PDSeqlist Psq)
{
free(Psq->data);
Psq->data =NULL;
Psq->usedsize = 0;
Psq->size =0;
}
void Show(PDSeqlist Psq)
{
for(int i = 0;i<Psq->usedsize ;i++)
{
printf("%d ",Psq->data[i]);
}
printf("\n");
}
int main()
{
DSqlist dq;
InitSeqlist(&dq);
printf("插入初始值\n");
for(int i = 1;i<=14;i++)
{
Insert(&dq,i-1,i);
Show (&dq);
}
printf("在3号位置插入100\n");
Insert(&dq,3,100);
Show (&dq);
printf("删除3号位置的数据\n");
DeletePos(&dq,3,NULL);
Show (&dq);
Destroy(&dq);
return 0;
}
执行结果如下: