定长顺序表的实现
定义
顺序表:是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。
存储结构:
存储的数据但在逻辑上是连续的,在存储 的物理空间上是不连续的。每个数据都有一个直接前驱和后继(除了第一个和最后一个)
定长顺序表:
存储的数据在逻辑上是连续的,在存储的物理空间上也是连续的。类似于数组
图例如下
功能的实现
1、初始化
2、插入
3、头插
4、尾插
5、按位置删除
6、头删
7、尾删
8、按值删除
9、按值查找
10、销毁
结构体
#define INITSIZE 100
typedef int ElemType;
typedef struct
{
ElemType *data;//data用来存储申请的空间的首地址
int length;//当前已存储的数据元素的个数
}FixedSqList;
初始化
void FixedSqListInit(FixedSqList *sq)//初始化
{
if (sq == NULL)
{
exit(0);//直接结束程序
}
sq->data = (ElemType*)malloc(sizeof(ElemType) * INITSIZE);
if (sq->data == NULL)
{
exit(0);
}
sq->length = 0;
}
插入
void FixedSqListInsert(FixedSqList *sq, ElemType val, int pos)
{
if (sq == NULL) exit(0);
if (sq->length == INITSIZE)
{
printf("Sqlist is Full\n");
return;
}
//对pos值合法性的判断
if (pos<0 || pos>sq->length)
{
printf("Insert pos is error\n");
return;
}
//将pos位置之后(包括pos位置)的元素统一向后挪动一个位置
for (int i = sq->length; i > pos; --i)
{
sq->data[i] = sq->data[i - 1];
}
//将val值存储到以pos作为下标的位置
sq->data[pos] = val;
sq->length++;
}
头插
void FixedSqListInsertHead(FixedSqList * sq, ElemType val)
{
FixedSqListInsert(sq, val, 0);
}
尾插
void FixedSqListInsertTail(FixedSqList *sq, ElemType val)
{
if (sq == NULL) exit(0);
FixedSqListInsert(sq, val, sq->length);
}
按位置删除
void FixedSqListDeletePos(FixedSqList *sq,int pos)
{
if (sq == NULL) exit(0);
if (pos<0 || pos>sq->length)
{
printf("Dlete:: pos is error\n");
return;
}
for (int i = pos; i < sq->length - 1; ++i)
{
sq->data[i] = sq->data[i + 1];
}
sq->length--;
}
头删
void FixedSqListDeleteHead(FixedSqList* sq)
{
FixedSqListDeletePos(sq, 0);
}
尾删
void FixedSqListDeleteTail(FixedSqList* sq)
{
if (sq == NULL) exit(0);
//顺序表已经是空的
if (sq->length == 0) return;
sq->length--;
}
按值删除
void FixedSqListDeleteValue(FixedSqList *sq,ElemType val)
{
if (sq == NULL) exit(0);
int count = 0;
for (int i = 0; i + count < sq->length;)
{
if (val == sq->data[i])
{
count++;
}
else
{
i++;
}
sq->data[i] = sq->data[i + count];
}
sq->length-=count;
}
按值查找
int FindValueLast(FixedSqList *sq, ElemType val)
{
if (sq == NULL) exit(0);
int index = -1;
for (int i = 0; i < sq->length; ++i)
{
if (sq->data[i] == val)
{
index = -1;
}
}
return index;
}
销毁
void FixedSqListDestroy(FixedSqList *sq)
{
if (sq == NULL) exit(0);
free(sq->data);
sq->data = NULL;//防止出现野指针
sq->length = 0;
}
此文章仅代表自己(本菜鸟)学习积累记录,或者学习笔记,如有侵权,请联系作者删除。人无完人,文章也一样,文笔稚嫩,在下不才,勿喷,如果有错误之处,还望指出,感激不尽~
技术之路不在一时,山高水长,纵使缓慢,驰而不息。