顺序表基础

线性表是n个具有相同特性的数据元素的有限序列。
线性表本质上就是数组,但是在数组的基础上,还要求数据是从头开始连续存储的,不能跳跃间隔。
顺序表是用一段物理地址连续的存储单元一次存储数据元素的线性结构。

#define N 100
typedef double SLDataType;

// 静态顺序表
typedef sruct Seqlist
{
	SLDataType a[N];
	int size;  // 表示数组中存储了多少个数组
}SL;

// 动态顺序表
typedef struct SeqList
{
	SLDataType* a;
	int size;  // 表示数组中存储了多少个数据
	intcapacity; // 数组实际鞥存储的空间容量是多大
}SL;
// 初始化顺序表
void SeqListInit(SL* ps)
{
	ps->a=NULL;
	ps->size = ps->capacity = 0;
}

// 销毁顺序表
void SeqListDestory(SL* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

// 顺序表插入
void SeqListPushBack(SL* ps, SLDataType x)
{
	// 如果容量不够,则进行扩容 
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity*sizeof(SLDataType));
		if (tmp == NULL) {
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = tmp;
		ps>capacity = newcapacity;
	}
	ps->a[ps->size] = x;
	ps->size++; 
}

// 顺序表尾删
void SeqListPopBack(SL* ps)
{
	if (ps->size >0) {
		ps->size--;
	}
}

// 顺序表插入
void SeqListPushFront(SL* ps, SLDataType x)
{
	// 挪动数据
	int end = ps->size -1;
	while (end >= 0) {
		ps->a[end] = ps->a[end + 1];
		--end;
	}
	ps->a[0] = x;
	ps->size++;
}

www.cplusplus.com/reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值