一:顺序表
特点:内存连续(数组)
1)逻辑结构:线性结构
2)存储结构:顺序存储
3)操作:增删改查
二:头文件定义
#ifndef _SEQLIST_H__
#define _SEQLIST_H__
#include <stdio.h>
#include<stdlib.h>
#define N 5
typedef struct seq
{
int data[N];
int last; //最后一个有效元素下表
}seqlist_t;
//1.创建一个空的顺序表
seqlist_t *CreateEpSeqlist();//返回的是申请空间的首地址
//2.向顺序表的指定位置插入数据
int InsertIntoSeqlist(seqlist_t *p, int post,int data);//post第几个位置,data插入的数据
//3.遍历顺序表sequence 顺序 list 表
void ShowSeqlist(seqlist_t *p);
//4.判断顺序表是否为满,满返回1 未满返回0
int IsFullSeqlist(seqlist_t *p);
//5.判断顺序表是否为空
int IsEpSeqlist(seqlist_t *p);
//6.删除顺序表中指定位置的数据post删除位置
int DeletePostSeqlist(seqlist_t *p, int post);
//7.清空顺序表
void ClearSeqList(seqlist_t *p);
//8.修改指定位置的数据
int ChangePostSeqList(seqlist_t *p,int post,int data);//post被修改的位置,data修改成的数据
//9.查找指定数据出现的位置
int SearchDataSeqList(seqlist_t *p,int data);//data代表被查找的数据
#endif
三:代码实现
#include "seqlist.h"
seqlist_t *CreateEpSeqlist() // 返回的是申请空间的首地址
{
seqlist_t *p = (seqlist_t *)malloc(sizeof(seqlist_t));
if (p == NULL)
{
// printf("开辟失败");
perror("开辟失败");
return NULL;
}
// 对last进行初始化
p->last = -1;
return p;
//(*p).last=-1;通过指向结构体变量的指针间接的去访问其中的成员:
// 格式: 指针变量名 -> 成员变量名
}
// 2.向顺序表的指定位置插入数据
int InsertIntoSeqlist(seqlist_t *p, int post, int data)
{
// 容错判断
if (post < 0 || post > p->last + 1 || IsFullSeqlist(p) == 1)
{
perror("InsertIntoSeqlist err");
return -1; // int类型为假返回-1,指针返回为NULL
}
// for循环遍历,从最后一位到要插入的位置
for (int i = p->last; i >= post; i--)
p->data[i + 1] = p->data[i]; // 拿到数组名之后,将最后一位到插入位置向后移动一个单位
p->data[post] = data; // 插入值
p->last++; // 最后一个有效元素下标加1
return 0;
}
// 3.遍历顺序表sequence 顺序 list 表
void ShowSeqlist(seqlist_t *p)
{
for (int i = 0; i <= p->last; i++)
printf("%d ", p->data[i]);
}
// 4.判断顺序表是否为满,满返回1 未满返回0
int IsFullSeqlist(seqlist_t *p)
{
return (p->last) - (N - 1);
// if(((p->last)-(N-1))==0)
// return 1;
// else
// return 0;
}
// 5.判断顺序表是否为空
int IsEpSeqlist(seqlist_t *p)
{
return p->last == -1;
}
// 6.删除顺序表中指定位置的数据post删除位置
int DeletePostSeqlist(seqlist_t *p, int post)
{
// 容错判断
if (post < 0 || post >= p->last + 1 || IsEpSeqlist(p) == 1)
{
perror("InsertIntoSeqlist err");
return -1; // int类型为假返回-1,指针返回为NULL
}
for (int i = post + 1; i <= p->last; i++)
{
p->data[i - 1] = p->data[i];
}
p->last--;
return 0;
}
// 7.清空顺序表
void ClearSeqList(seqlist_t *p)
{
p->last = -1;
}
// 8.修改指定位置的数据
int ChangePostSeqList(seqlist_t *p, int post, int data) // post被修改的位置,data修改成的数据
{
if (post < 0 || post > p->last + 1 || IsEpSeqlist(p))
{
perror("err\n");
return -1;
}
p->data[post] = data;
return 0;
}
// 9.查找指定数据出现的位置
int SearchDataSeqList(seqlist_t *p, int data) // data代表被查找的数据
{
int num=0;
for (int i = 0; i <= p->last; i++)
{
if (data == p->data[i])
num = i;
}
return num;
}