【数据结构森林】拨开简单的顺序表

我在大学的课堂,觉得数据结构很难理解。不过课后很幸运地借助资料自学了下来。感觉又有什么复杂的呢?无非老师没给我讲清楚罢了。那么我们开始入门:顺序表。

顺序表可以理解为一个长度为SIZE的数组a[SIZE],数组中的每一个元素都有下标,而我们则是通过一个个下标去1插入数组,2删除数组,3遍历数组,4寻找数组中的值。这四步就是顺序线性表的主要操作了。

1.首先定义全局变量:最大长度SIZE,和实时长度ListSize

#define SIZE 10

int ListSize = 10;

2.定义名为List的变量,使它的作用与int相当(之所以不直接用int表示是因为数组元素还可以用其他变量类型去定义, 例如char。届时只要将List再定义为char就ok了)

typedef int List;

3.定义四个函数分别为ListInsert(), ListDelete(), ListTravel(), ListFindElement()。如果一个个分开说文章就太没结构了。所以我一次性把全代码先贴出来。


#include<stdio.h>
#define SIZE 10
typedef int List;
int ListSize = 0;
int ListInsert(List *list, List a){
if(list == 0)
return 1;
if(ListSize >= SIZE){
printf("the list is full\n");
return 1;
}
list[ListSize++] = a;
return 0;

}
int ListDelete(List *list, List a){
int index;
if(ListSize <= 0){
printf("the list is empty\n");
return 1;
}
for(index = 0; index < ListSize && index < SIZE; index++){
if(list[index] == a){
list[index] = 0;
ListSize--;
return 0;
}
}
return 0;
}
int ListTravel(List *list){
int index;
if(ListSize == 0){
printf("the list is empty\n");
return 1;
}
printf("the travel result:");
for(index = 0; index < ListSize && index < SIZE; index++){
printf("%d ", list[index]);
}
return 0;
}
int ListFindElement(List *list, List a){
int index;
if(ListSize == 0){
printf("the list is empty\n");
return 1;
}
printf("the finding result is:");
for(index = 0; index < ListSize && index < SIZE; index++){
if(list[index] == a){
return 0;
}
}
return -1;
}
int main(){
List list[SIZE] = {0};
int i = 0;
for(i = 0; i < 5; i++){
list[i] = i;
ListSize++;
}
ListTravel(list);
ListInsert(list, 1);
ListTravel(list);
ListDelete(list,4);
ListTravel(list);
int a = ListFindElement(list,2);
printf("%d",a);
return 0;
}

若具体不懂请在评论提问,有什么想要我讲的数据结构内容也可以提出

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据结构森林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值