1、 结构体设计:
代码:
#define MAX_SIZE 100
//定长顺序表
typedef struct sqlist
{
int arr[MAX_SIZE];//存放有效数据 是一个静态数组
int length; //存放有效值个数
}sqlist, *Psqlist;
2、定长顺序表的基本操作
(1)初始化
//将定义的struct sqlist普通成员变量进行初始化
void Init_sqlist(struct sqlist *p)//void Init_sqlist(Psqlist p);
{
assert(p!=NULL);
if(p == nullptr)
return;
//p->arr; 数组不需要赋值 因为里面值有没有效用 是根据length来判定
p->length = 0;
}
(2)按位置插入
//按位置插入
bool Insert_pos(Psqlist p, int pos, int val)//参数为顺序表的指针、插入位置、插入值
{
//1.判空 p!=NULL 判断定长顺序表是否存在
assert(p!=NULL);
if(p == NULL)
return false;
//2.判断插入位置 是否合法
assert(pos >=0 && pos<=p->length);// 插入的时候pos==p->length合法
if(pos <0 || pos>p->length)
return false;
//3.判满操作
if(IsFull(p))
return false; //没有扩容的定长顺序表 不需要执行扩容函数
//4.首先挪动数据,让待插入位置空出来,再将值val放进去即可
//(插入,挪动数据,从后先前挪)
for(int i=p->length-1; i>=pos; i--)//i初始时指向最后一个元素下标
{
p->arr[i+1] = p->arr[i];//不要写反
}
//此时,for循环执行结束 标识着挪动数据完成 现在只需要将插入的值val赋值进去
p->arr[pos] = val;
p->length++;
return true;
}
(3)按位置删除
bool Del_pos(Psqlist p, int pos)
{
//1.判空 p!=NULL 判断定长顺序表是否存在
assert(p!=NULL);
if(p == NULL)
return false;
//2.判断删除位置 是否合法
assert(pos >=0 && pos<p->length);// 删除的时候pos==p->length不合法
if(pos<0 || pos>=p->length)
return false;
//3.判空操作
if(IsEmpty(p))
return false;
//4.将待删除位置后面的有效值,一次向前挪动一位,将删除位置覆盖掉即可
//(删除,向前覆盖数据,离待删除位置最近的元素先挪动)
for(int i=pos+1; i<=p->length-1; i++)//i<=p->length-1 == i<p->length
{
p->arr[i-1] = p->arr[i];
}
//此时,for循环执行结束 标识着数据向前覆盖完成 现在只需要将p->length--
p->length--;
return true;
}
(4)按值删除
//按值删除
bool Del_val(Psqlist p, int val)
{
//assert
int index = Search(p, val);//调用按值查找,返回其位置
if(index == -1)
return false;
return Del_pos(p, index);//调用按位置删除函数
}
(5)获取有效长度
//获取其有效长度
int Get_length(Psqlist p)
{
return p->length;
}
(6)按值获取下标
//获取值所在下标(如果数据重复,则返回val第一次出现的位置)
int Search(Psqlist p, int val)
{
//assert
for(int i=0; i<p->length; i++)
{
if(p->arr[i] == val)
{
return i;
}
}
return -1;
}
(7)判空、判满操作
//判空
bool IsEmpty(Psqlist p)
{
return p->length==0;
}
//判满
bool IsFull(Psqlist p)
{
return MAX_SIZE==p->length;
}
(8)清空、销毁、打印操作
//清空
void Clear(Psqlist p)
{
//assert
p->length = 0;
}
//销毁 释放动态内存,防止内存泄露
void Destroy(Psqlist p)
{
//assert
Clear(p);
//因为定长顺序表 存放数据用的是静态数组 系统开辟系统释放
}
//打印
void Show(Psqlist p)
{
//assert
for(int i=0; i<p->length; i++)
{
printf("%d ", p->arr[i]);
}
printf("\n");
}
3、主函数调用各个操作函数
#include <stdio.h>
#include "assert.h"
#include <stdlib.h>
#include "sqlist.h"
#include <vld.h>
int main()
{
struct sqlist head;//定义一个定长顺序表head
Init_sqlist(&head);//初始化
printf("length = %d\n", Get_length(&head));//打印长度
for(int i=0; i<10; i++)//按位置插入1-10
{
Insert_pos(&head, i, i+1);
}
Insert_pos(&head, 0, 100);//在0号位置插入数字100
Insert_pos(&head, head.length, 200);//尾插200
printf("length = %d\n", Get_length(&head));
Show(&head);
Del_pos(&head, 3);
Show(&head);
Del_val(&head, 9);
Show(&head);
printf("%d\n", Search(&head, 5));
printf("%d\n", Search(&head, 300));
Clear(&head);
printf("length = %d\n", Get_length(&head));
Show(&head);
Destroy(&head);
return 0;
}