线性表:数据元素关系为线性关系的逻辑结构
线性表的存储结构:
存储线性表时,除了要存储具体线性表的数据意外,还要存储数据与数据之间的关系(
线性关系、线性结构、先后关系)
顺序存储:数据在存储时,申请的是一段连续的内存空间,把数据存储到这段连续空间(地址相邻)中。
线性表的顺序存储:存储数据元素时,把数据元素按照逻辑关系(先后顺序),依次存储在一段连续的内存空间,借助元素在这段连续空间的地址,来表示数据之间的先后关系,就叫做顺序存储。
顺序表的运算:要满足顺序表结构要求
1. 增加数据
2. 删除数据
3. 修改数据
4. 查找数据
5. 判断满
6. 判断空
7. 求表长
8. 创建表
9. 清空表
下面是示例程序
#include <stdio.h>
#include <stdlib.h>
struct book
{
char name[20];
char autor[20];
int No;
};
struct array
{
int num;
//struct book Book[50];
int Nos[5];//定义20个元素,每个元素 int类型来表示一本书的编号
};
struct array * create()
{
//申请的空间是一个结构体,返回结构体的地址
//想访问也是按照结构体进行访问,按照结构体的类型进行操作,所以地址也应该是结构体的地址
struct array * p = malloc(sizeof(struct array));
if(p == NULL)
{
printf("malloc error\n");
return NULL;
}
p->num = 0;
return p;
}
int full(struct array *p)
{
if(p->num == 5)
{
printf("is full\n");
return 1;
}
return 0;
//return p->num == 20 ? 1 : 0;
}
void add(struct array * p,int pos,int no)
{
if(full(p))
{
return ;
}
//int i = p->num-1;
if(pos > p->num-1)
{
p->Nos[p->num] = no;
}
else
{
for(int i = p->num;i > pos ;i--)
{
p->Nos[i] = p->Nos[i-1];
}
p->Nos[pos] = no;
}
p->num++;
}
int empty(struct array *p)
{
if(p->num == 0)
{
printf("is empty\n");
return 1;
}
return 0;
}
void del(struct array * p,int pos,int *k)
{
if(empty(p))
{
return ;
}
if(pos > p->num-1)
{
printf("pos error\n");
*k = 0;
return ;
}
*k = p->Nos[pos];
int i = pos;
for(int i = pos;i < p->num-1 ; i++)
{
p->Nos[i] = p->Nos[i+1];
}
p->num--;
}
void up(struct array * p,int pos,int no)
{
if(pos >= p->num)
{
printf("up data pos error\n");
return ;
}
p->Nos[pos] = no;
}
void search(struct array * p,int pos)
{
if(pos >= p->num)
{
printf("search data pos error\n");
return ;
}
printf("book number is %d\n",p->Nos[pos]);
}
void show(struct array * p)
{
for(int i = 0;i < p->num;i++)
{
printf("%d ",p->Nos[i]);
}
printf("\n");
}
int main()
{
int k;
struct array * arraylist = create();
show(arraylist);
del(arraylist,1,&k);
printf("del data is %d\n",k);
add(arraylist,10,110);
add(arraylist,10,99);
add(arraylist,10,120);
show(arraylist);
add(arraylist,1,999);
show(arraylist);
return 0;
}