以下注意点
- 数据结构那本书中目的是为了让读者更好的理解思路;
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
#define InitLong 100
#define true 1
#define false 0
typedef int ElemType;
typedef int bool;
// 静态结构
typedef struct{
ElemType data[MaxSize];
int length;
}Seqlist;
// 动态结构
typedef struct{
ElemType *data;
int MaxLong,length;
}Sqlist;
// 所有操作仅针对 动态结构 ;
// 初始化操作
bool ListInit(Sqlist *L);
// 输出操作 输出 所有 data 的数据
void Print(Sqlist L);
// 插入操作
bool ListInsert(Sqlist *L,int i,ElemType e);
// 删除操作 在 L 中删除指定 位序的元素并将 删除元素e 用应用变量保存, 成功 true 失败 false
bool ListDelete(Sqlist *L,int i,ElemType *e);
// 查找操作 在 L 中找第一个 值为 e 的元素返回其位序
int ListLocate(Sqlist *L,ElemType e);
// 销毁操作
void ListDestory(Sqlist *L);
bool ListInit(Sqlist *L){
L->length = 0;
L->MaxLong = 50;
L->data = (ElemType *)malloc(sizeof(ElemType)*InitLong);
if(L->data == NULL)return false;
else return true;
}
void Print(Sqlist L){
if(L.length == 0)printf("this is empty table");
for(int i = 0;i<L.length;i++){
printf("{NO.[%d] is %d } ",i+1,L.data[i]);
}
printf("\n");
}
bool ListInsert(Sqlist *L,int i,ElemType e){
if(i<1||i>L->length+1)return false;
if(L->length==L->MaxLong)return false;
for(int j = L->length;j>=i;j--){
L->data[j] = L->data[j-1];
}
L->data[i-1] = e;
L->length++;
return true;
}
bool ListDelete(Sqlist *L,int i ,ElemType *e){
if(i<0||i>L->length)return false;
*e = L->data[i-1];
for(i;i<L->length;i++){
L->data[i-1] = L->data[i];
}
L->length--;
return true;
}
int ListLocate(Sqlist *L,ElemType e){
int temp;
for(int i = 0;i<L->length;i++){
if(L->data[i]==e){
return i+1;
}
}
return 0;
}
void ListDestory(Sqlist *L){
L->data = NULL;
L->length = 0;
L->MaxLong = 0;
}
int main(){
Sqlist L;
// 初始化
if(ListInit(&L))printf("init succeed\n");
else printf("init defeat");
// 插入元素
for(int i = 0;i<=9;i++){
if(ListInsert(&L,1,i))printf("insert %d succeed\n",i);
else printf("insert defead");
}
Print(L);
//删除元素
ElemType *e;
ListDelete(&L,2,e);
printf("delete element is e = %d \n",*e);
Print(L);
//查找元素
ElemType e1 = 6;
int locate;
locate = ListLocate(&L,e1);
printf("the e1 locate is %d \n",locate);
//
ListDestory(&L);
Print(L);
return 0;
}