按照顺序存储:
顺序表
按照链式存储:
链表 (单向链表 双向链表 内核链表 )
数据只有一个前驱和一个后继,数据紧挨保存。
具体实现:
数组:int arr[100];
弊端:100个元素,我只初始化了50个,但是遍历的时候,100个元素全部都会被遍历出来。
改进:(使用结构体)
struct seq{
int arr[100]; // 数据保存的地方
int len; // 有效数据个数
};
这样的话,就可以只遍历我们使用到的部分。
顺序表的优点缺点:
缺点:添加数据 删除数据 非常麻烦
优点:查询,替换数据非常方便(下标)
#include
#include
#define N 7
typedef int datatype;
struct seqlist{ //先定义一个结构体
datatype data[N]; //定义一个长度为7的数组
int len; //数组中,有效数据的个数
};
struct seq *seq_init(void)
{
struct seq *p = (struct seq *)malloc(sizeof(struct seq));//在堆中开辟空间
if(p == NULL) // malloc 出错处理
{
perror("seq_init malloc error");
return NULL;
}
p->len = 0; //由于一开始没有数据插入数组,所以此时数组中存储的有效数据的个数为0
return p;
}
void seq_add(struct seq *p,datatype d,unsigned int loc)
{
//判断顺序表是否存满
if(p->len == N){
printf("sorry!满了n");
return; //结束函数
}
if(loc<1 || loc > p->len+1)
{
printf("您的位置不合法n");
return; //结束函数
}
int i;
for(i=p->len;i>=loc;i--){ //从位置loc( 即:data[loc-1] ) 开始往后,将数据依次往后面挪动一个位置,留出一个空位,好让新数据插入空位中
p->data[i]=p->data[i-1];
}
p->data[loc-1]=d; //将数据插入刚才留出来的空位中
p->len++; //新数据插入后,数组长度+1,所以,我们需要在这里手动更新一下数组中存储的有效数据的个数+1
}
int seq_del(struct seq *p,unsigned int loc,datatype *d)
{
//判断位置是否合法,或者为空
if(loc<1 || loc > p->len)
{
printf("您的位置不合法n");
return -1; //结束函数
}
// 删除数据
*d = p->data[loc-1]; //将需要删除的数据传出去
int i;
for(i=loc;i<=p->len-1;i++){
p->data[i-1]=p->data[i];
}
p->len--; // 整个有效数据长度-1
return 0;
}
void seq_update(struct seq *p,datatype old,datatype new)
{
int i;
for(i=0;i
if(old == p->data[i])
p->data[i]=new;
}
}
void display(struct seq *p)
{
printf("遍历结果为:");
int i;
for(i=0;i
printf("%d ",p->data[i]);
}
printf("n");
}



