顺序表 c语言实现

目录

顺序表:

函数声明:

初始化:

函数空间检查与扩容:

头插,头删,尾插,尾删:

特定位置的删除与插入:


顺序表:

  • 概念部分:顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储,在数组上完成数据的增删查改。
  • 顺序表一般分为:静态顺序表,动态顺序表

顺序表C语言实现:

首先你需要明确,你需要的基础功能应该有那些:

  1. 头插,头删
  2. 尾插,尾删
  3. 扩容
  4. 初始化
  5. 特定位置删除与插入

接下来开始实现:

在数据结构阶段应该将函数声明与实现分开来,养成好的代码习惯。

函数声明:

//初始化
void SLInit(SL* ps);

//检查空间
void SLcheckcapacity(SL*ps);

//尾插 尾删(o(1))      头插 头删(0(n))
void SLPushBack(SL* ps, SLDatatype x);

void SLPopBack(SL* ps);

void SLPushFront(SL* ps, SLDatatype x);

void SLPopFront(SL* ps);

//特定位置插入 删除
void SLinsert(SL* ps, int pos, SLDatatype x);//pos 位置

void SLerase(SL* ps, int pos);

//输出函数
void SLprint(SL* ps);

 首先需要创建一个结构体,我们需要有指向动态数组的指针,数组的空间容量,数组的有效元素。

typedef int SLDatatype;

typedef struct Seqlist {
	SLDatatype* a;//指向动态数组指针
	int size;//数据个数
	int capacity;//容量-空间大小
}SL;

接下来,开始实现各部分功能:

初始化:

void SLInit(SL* ps) {

	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

函数空间检查与扩容:

void SLcheckcapacity(SL* ps) {
	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 fall\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}

}

头插,头删,尾插,尾删:

void SLPushFront(SL* ps, SLDatatype x) {
	SLcheckcapacity(ps);
	int end = ps->size - 1;
	while (end >= 0) {
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;

}

void SLPopFront(SL* ps) {
	assert(ps->size > 0);
	int begin = 1;
	while (begin < ps->size) {
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;

}
void SLPushBack(SL* ps,SLDatatype x) {
	SLcheckcapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

void SLPopBack(SL* ps) {
	assert(ps->size > 0);
	ps->size--;
	
	
}

特定位置的删除与插入:

void SLinsert(SL* ps, int pos, SLDatatype x) {
	assert(ps&&pos>=0&&pos<ps->size);
	SLcheckcapacity(ps);
	int end = ps->size - 1;
	while (end >=pos) {
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}


void SLerase(SL* ps, int pos) {
	assert(ps && pos >= 0 && pos < ps->size);
	SLcheckcapacity(ps);
	int begin = pos;
	while (begin < ps->size - 1) {
		ps->a[begin] = ps->a[begin + 1];
		begin++;
	}
	ps->size--;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值