#include <stdio.h>
#include "assert.h"
#include <stdlib.h>
#include "sqlist.h"
//1.还是首先回去编译器默认库函数文件里去找 2.自定义路径去找
//注意事项:插入和删除的时候,记着p->length,++或者--一下
//将定义的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;
}
//按位置插入
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;
}
//按位置删除
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;
}
//按值删除
bool Del_val(Psqlist p, int val)
{
//assert
int index = Search(p, val);
if(index == -1)
return false;
return Del_pos(p, index);
}
//获取其有效长度
int Get_length(Psqlist p)
{
return p->length;
}
//扩容 这里这个函数不需要实现 因为是定长顺序表
//获取值所在下标(如果数据重复,则返回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;
}
//判空
bool IsEmpty(Psqlist p)
{
return p->length==0;
}
//判满
bool IsFull(Psqlist p)
{
return MAX_SIZE==p->length;
}
//清空
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");
}
#include <stdio.h>
#include "assert.h"
#include <stdlib.h>
#include "sqlist.h"
#include <vld.h>
int main()
{
struct sqlist head;
Init_sqlist(&head);
printf("length = %d\n", Get_length(&head));
for(int i=0; i<10; i++)
{
Insert_pos(&head, i, i+1);
}
Insert_pos(&head, 0, 100);
Insert_pos(&head, head.length, 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;
}