定长顺序表,我们可以看出一个数组,因为不需要扩容,没有必要用到malloc。
存储如下图
头文件FixedLengthSqList.h
#pragma once//防止头文件重复
typedef int ELEM_TYPE;
#define SIZE 20
//结构体声明
typedef struct SqList
{
ELEM_TYPE data[SIZE]; //不扩容的顺序表
int length; //顺序表的有效元素个数
}SqList,*PSqList;
//初始化(将结构体的成员变量赋初值)
void Init_SqList(SqList *p);
//任意位置插入数据
int Insert_Pos(SqList *p,int pos,int value);
//任意位置删除元素
int Delete_Pos(SqList *p,int pos);
//查找元素所在第一个位置
int Search(SqList *p,int value);
//判空
int IsEmpty(SqList *p);
//判满
int IsFull(SqList *p);
//打印顺序表
void print(SqList *p);
//清空
void Clear(SqList *p);
//销毁
void Destory(SqList *p);
函数定义FixedLengthSqList.h
#include <stdio.h>
#include <assert.h>
#include "FixedLengthSqList.h"
//初始化(将结构体的成员变量赋初值)
void Init_SqList(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
return ;
}
p->length = 0;
}
//任意位置插入数据
int Insert_Pos(SqList *p,int pos,int value)
{
assert(p != NULL && pos <= p->length && pos >= 0);
if (p == NULL)
{
printf("Sequque error\n");
return 0;
}
if(pos < 0 || pos > p->length)
{
printf("pos error\n");
return 0;
}
if(IsFull(p))
{
printf("Sequense has fulled\n");
return 0;
}
int i = p->length;
for(;i > pos;i--)
{
p->data[i] = p->data[i - 1];
}
p->data[pos] = value;
p->length++;
return 1;
}
//任意位置删除元素
int Delete_Pos(SqList *p,int pos)
{
assert(p != NULL && pos >= 0 && pos < p->length);
if (p == NULL)
{
printf("Sequense has fulled\n");
return -1;
}
if(pos < 0 || pos > p->length)
{
printf("pos error\n");
return 0;
}
int i = pos;
for(;i < p->length;i++)
{
p->data[i] = p->data[i + 1];
}
p->length --;
return 1;
}
//查找元素所在第一个位置
int Search(SqList *p,int value)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return -1;
}
int i = 0;
for(;i < p->length;i++)
{
if(p->data[i] == value)
{
return i;
}
}
return -1;
}
//判空
int IsEmpty(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return 0;
}
return p->length == 0;
}
//判满
int IsFull(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return 0;
}
return p->length == SIZE;
}
//打印顺序表
void print(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return ;
}
int i = 0;
for(;i < p->length;i++)
{
printf("%d -> ",p->data[i]);
}
printf(" NULL\n");
}
//清空
void Clear(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return ;
}
p->length = 0;
}
//销毁(栈里面开辟的空间,系统开辟,系统释放)
void Destory(SqList *p)
{
assert(p != NULL);
if (p == NULL)
{
printf("Sequense has fulled\n");
return ;
}
p->length = 0;
}
主函数main.c
#include<stdio.h>
#include"FixedLengthSqList.h"
int main()
{
SqList sq;
Init_SqList(&sq);
IsEmpty(&sq);
Insert_Pos(&sq, 0, 0);
Insert_Pos(&sq, 1, 1);
Insert_Pos(&sq, 2, 2);
Insert_Pos(&sq, 3, 3);
print(&sq);
Delete_Pos(&sq,2);
print(&sq);
return 0;
}
测试结果