线性表的顺序存储
2015-03-24 16:23
267 查看
欢迎大家访问我的微博:http://weibo.com/u/2887401030
结果:
insert 20 error
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
delete num:0
可以看到最后的结果中,最后一个20因为超出了数组大小,所以insert error;其他的也都在我们意料之中。这里讲解的顺序线性表与大家学的教材里的略有不同,大家可以细细体会(讲解都在注释中)。最好是把这文件分成三分,一分头文件,一份c文件,一份测试文件。最佳的结果是测试文件并不知道线性表的结构,只是能用。这样的效果最棒,大家可以试试。
#include<stdio.h> #include<stdlib.h> typedef int ElemType; #define MAXSIZE 20 typedef struct SqList { ElemType data[MAXSIZE]; int length; }SqList; SqList* Create_List() { SqList *list = (SqList *)malloc(sizeof(SqList)); if(list == NULL) { return NULL; } list->length = 0; return list; } //在i位置插入一个数据 int Insert_List(SqList *list,int i,ElemType data) { int n; if(list == NULL) { return -1; } if(i < 0|| i >= MAXSIZE)//保证序号正确 { return -2; } if(list->length >= MAXSIZE) { return -3;//已满 } //1 5 3 7 4 . . for(n = list->length-1;n >= i;n--) { //位置后移,并赋值 list->data[n+1] = list->data ; } //插入数据 list->data[i] = data; list->length++; return 0; } //在i位置删除一个数据,并用value返回该值 int Delete_List(SqList *list,int i,ElemType *value) { int n; if(list == NULL) { return -1; } if(i < 0|| i >= MAXSIZE)//保证序号正确 { return -2; } //位移前,先赋值 *value = list->data[i]; //1 5 3 7 4 . . for(n = i + 1;n >= list->length - 1;n--) { //位置前移,并赋值value list->data = list->data[n+1]; } list->length--; return 0; } //在i位置得到一个数据,并用value返回该值 int Get_List(SqList *list,int i,ElemType *value) { if(list == NULL) { return -1; } if(i < 0|| i >= MAXSIZE || list->length == 0)//保证序号正确 { return -2; } *value = list->data[i]; return 0; } void Destroy_List(SqList *list) { if(list == NULL) { return -1; } free(list); } int main() { int i = 0,value = 0; SqList *list = Create_List(); for(i=0;i<=list->length;i++) //故意多一个 { if(Insert_List(list,i,i) != 0) { printf("insert %d error\n",i); } } for(i=0;i<list->length;i++) { Get_List(list,i,&value); printf("%2d ",value); } Delete_List(list,0,&value); printf("\ndelete num:%d\n",value); Destroy_List(list); return 0; }
结果:
insert 20 error
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
delete num:0
可以看到最后的结果中,最后一个20因为超出了数组大小,所以insert error;其他的也都在我们意料之中。这里讲解的顺序线性表与大家学的教材里的略有不同,大家可以细细体会(讲解都在注释中)。最好是把这文件分成三分,一分头文件,一份c文件,一份测试文件。最佳的结果是测试文件并不知道线性表的结构,只是能用。这样的效果最棒,大家可以试试。