栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

C语言顺序表(源码)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言顺序表(源码)

目录

静态顺序表

初始化

 尾插

打印表

动态顺序表

初始化

扩容

头插

尾插

中间任意位置插

头删

尾删

中间任意位置删

打印表

释放空间


插入的三种方法:

删除的三种方法:

 


静态顺序表

初始化
//数据结构
#define MAX_SIZE 10
typedef int type;

typedef struct seqlist {
	type arr[MAX_SIZE];
	int count;
}Seq;


//初始化数据
void Init(Seq* list)
{
	memset(list->arr, 0, sizeof(int) * MAX_SIZE);
	list->count = 0;
}

 尾插
//尾插
void PushBack(Seq* list,type x)
{
	if (list->count == MAX_SIZE)
	{
		printf("Error,ñn");
		return;
	}
	list->arr[list->count] = x;
	list->count++;

}

打印表
//打印表
void Print(Seq* list)
{
	int i = 0;
	for (i = 0; i < list->count; i++)
	{
		printf("%d ", list->arr[i]);
	}
}


动态顺序表

初始化
//定义一个表
typedef int type;

typedef struct Seqlist {
	type* arr;
	int count;
	int capacity;
}Seq;


//初始化表
void Inint(Seq* list)
{
	list->arr = NULL;
	list->count = 0;
	list->capacity = 0;
}

扩容
//扩容
void Enlarge(Seq* list)
{
	//先判断是否放满
	if (list->count == list->capacity)
	{
		//动态增大容量
		int newcapacity = list->capacity == 0 ? 4 : list->capacity * 2;
		//扩大内存
		type* pa = (type*)realloc(list->arr, newcapacity * sizeof(type));
		if (pa == NULL)
		{
			printf("开辟失败n");
			return;
		}
		list->arr = pa;
		list->capacity = newcapacity;
	}
}

头插
//头插
void PushFront(Seq* list, type x)
{
	//先把前面的所有数据向后移动一次
	int end = list->count - 1;
	while (end-- >= 0)
	{
		list->arr[end + 1] = list->arr[end];
	}
	//把x放到头位置
	list->arr[0] = x;
	list->count++;
}

尾插
//尾插
void PushBack(Seq* list,type x)
{
	list->arr[list->count] = x;
	list->count++;
}

中间任意位置插
//中间任意位置插
void PushInsert(Seq* list,int pos,int x)
{
	//判断是否已放满
	//可以调用扩容函数
	//这里假设已经调用
	//判断,目标位置不能大于现有数量
	assert(pos <= list->count);
	//先将从该位置的数据全部依次向后移一位(从头开始)
	int end = list->count - 1;
	while (end >= pos)
	{
		list->arr[end + 1] = list->arr[end];
		end--;
	}
	//插入
	list->arr[pos] = x;
	list->count++;
}

头删
//头删
void DelFront(Seq* list)
{
	int start = 1;
    //后面的数据依次往前移(从头开始)
	while (start <= list->count)
	{
		list->arr[start - 1] = list->arr[start];
		start++;
	}
	list->count--;
}

尾删
//尾删
void DelBack(Seq* list)
{
	//直接将最后一个数据扔掉
	list->count--;
}

中间任意位置删
//任意位置删
void DelInsert(Seq* list, int pos)
{
	//判断一下要删除的位置在不在已存的数据列内,否则没有意义
	assert(pos <= list->count);
	int start = pos + 1;
	while (start <= list->count)
	{
		list->arr[start - 1] = list->arr[start];
		start++;
	}
	list->count--;
}
打印表
//打印表
void Print(Seq* list)
{
	int i = 0;
	for (i = 0; i < list->count; i++)
	{
		printf("%d ", list->arr[i]);
	}
}

释放空间
//释放空间
void Free(Seq* list)
{
	//一定要记得是:先释放再置空,否则会成野指针,永远丢失空间
	free(list->arr);
	list->arr = NULL;
	list->count = 0;
	list->capacity = 0;
}


 

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038957.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号