动态顺序表的实现

顺序表的插入:

静态顺序表:如果满了,不处理 / 报错;

动态顺序表:如果满了,加入扩容机制。

实现代码如下:

#include <stdlib.h>
#include <assert.h>

typedef int DataType;

#define INIT_CAPACITY (3)

typedef struct SeqListD{
	DataType *parray;
	int capacity;	// 当前容量 等于 静态顺序表 MAX_SIZE
	int size;		// 同静态顺序表
}	SeqListD;

// 初始化/销毁/所有插入(尾插)
// 其他和静态顺序表完全一样

//初始化
void SeqListDInit(SeqListD *pSeq)
{
	//为了获得容量空间
	pSeq->capacity = INIT_CAPACITY;
	pSeq->parray = (DataType*)malloc(sizeof(DataType)*pSeq->capacity);
	assert(pSeq->parray);

	//这个和顺序表一样
	pSeq->size = 0;
}

//销毁
void SeqListDDestroy(SeqListD *pSeq)
{
	free(pSeq->parray);

	pSeq->capacity = 0;
	pSeq->parray = NULL;
	pSeq->size = 0;
}

// 头插
static void ExpandIfRequired(SeqListD *pSeq);
void SeqListDPushBack(SeqListD *pSeq, DataType data)
{
	//动态线性表,如果满了则加入扩容机制
	ExpandIfRequired(pSeq);

	pSeq->parray[pSeq->size] = data;
	pSeq->size++;
}

//扩容
static void ExpandIfRequired(SeqListD *pSeq)
{
	//扩容条件
	if (pSeq->size < pSeq->capacity)
	{
		return ;
	}

	// 扩容
	pSeq->capacity *= 2;

	// 1.申请新空间
	DataType *newArray = (DataType *)malloc(sizeof(DataType)* pSeq->capacity);
	assert(newArray);
	// 2.数据搬移
	for (int i = 0; i < pSeq->size; i++)
	{
		newArray[i] = pSeq->parray[i];
	}
	// 3.释放老空间,关联老空间
	free(pSeq->parray);
	pSeq->parray = newArray;
}

测试函数与主函数:

void Test()
{
	SeqListD sld;
	SeqListDInit(&sld);

	SeqListDPushBack(&sld, 1);
	SeqListDPushBack(&sld, 2);
	SeqListDPushBack(&sld, 3);
	//  这下面会扩容
	SeqListDPushBack(&sld, 4);
	SeqListDPushBack(&sld, 5);
}

int main()
{
	Test();
	return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值