顺序表实现简述

该文章描述了一个简单的顺序表(SQList)结构,包括数组元素arr、元素个数size和顺序表容量capacity。在SQList.c文件中实现了初始化、打印、尾部插入、尾部删除和销毁等基本操作。测试程序展示了如何使用这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结构:

sqlist.h:

顺序表元素:数组元素arr,元素个数size, 顺序表容量capacity

sqlist.c:

实现函数:创建init,输出print,尾插pushback,尾删popback,清空destroy;

#include"SeqList.h"
//初始化
void SLInit(SL* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->capacity = 0;
	ps->size = 0;
}
//输出
void SLPrint(SL* ps)
{
	assert(ps);//判空
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d", ps->arr[i]);
	}
	printf("\n");
}
//删除
void SLDestroy(SL* ps)
{
	assert(ps);
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
		ps->capacity = 0;
		ps->size = 0;
	}
}
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newCapaCity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* temp = (SLDataType*)realloc(ps->arr, newCapaCity * sizeof(SLDataType));
		if (temp == NULL)
		{
			perror("realloc erro");
			exit(-1);
		}
		ps->arr = temp;
		ps->capacity = newCapaCity;
	}
	ps->arr[ps->size] = x;
	ps->size++;

}
//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size>0);
	//ps->arr[ps->size - 1] = NULL;//多余
	ps->size--;

}







SeqList.c:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//静态顺序表
//#define	N 10
typedef int SLDataType;
//typedef struct SeqList
//{
//	 SLDataType arr[N];
//	 int size;
//}SL;
//动态顺序表
typedef struct SeqList
{
	SLDataType* arr;
	 int size;//元素个数
	 int capacity;//表长
}SL;
//创建
void SLInit(SL* ps);
//输出
void SLPrint(SL* ps);
//删除
void SLDestroy(SL* ps);
//尾插
void SLPushBack(SL* ps,SLDataType x);
//尾删
void SLPopBack(SL* ps);




test.c
#include"SeqList.h"
void TestSeqList()
{
	SL sl;
	SLInit(&sl);
	SLPushBack(&sl, 1);
	SLPushBack(&sl, 2);
	SLPushBack(&sl, 3);
	SLPushBack(&sl, 4);
	SLPushBack(&sl, 5);
	SLPushBack(&sl, 6);
	SLPrint(&sl);
	SLDestroy(&sl);
}
int main()
{
	TestSeqList();
	return 0;
}

test.c:

main中使用

注意:

assert暴力检查是否为空

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值