我在大学的课堂,觉得数据结构很难理解。不过课后很幸运地借助资料自学了下来。感觉又有什么复杂的呢?无非老师没给我讲清楚罢了。那么我们开始入门:顺序表。
顺序表可以理解为一个长度为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;
}
若具体不懂请在评论提问,有什么想要我讲的数据结构内容也可以提出