01_线性表
一、线性表的顺序存储
逻辑上相邻的数据元素,物理次序也相邻。占用连续存储空间,用“数组”实现,知道初始位置就可推出其他位置。
00_宏定义
// 函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
// Status是函数类型,其值表示函数结果状态
typedef int Status;
typedef char ElemType;
01_构建存储结构
// 表的名称和长度
#define SQLMAXSIZE 100;
typedef int SqlElemType;
/*
typedef struct {float p;int e;
}SqlElemType;
*/
typedef struct __Sqlist{SqlElemType *base; // 存储空间的基地址,后面用malloc动态分配内存int length;
}Sqlist;
备注:int max(int a[])和int max(int a[100])和int max(int a[0])三者等效。
02_初始化线性表
Status InitSL(Sqlist *L, int length){L->base = (SqlElemType *)malloc(sizeof(SqlElemType) * SQLMAXSIZE);if (!L->base) return OVERFLOW;L->length = 0; for (int i = 0; i < length + 1; i++){SqlElemType e;scanf(" %d", &e);SqlInsert(L, i, e);}return OK;
}
03_获取第position个元素
Status GetElem(Sqlist *L, int position, SqlElemType *e){if (position < 1 || position > L->length)return ERROR;*e = L->base[position -1];return OK;
}
04_查找与给定元素e相同的元素
Status LocatElem(Sqlist *L ,SqlElemType e){for (int i = 0; i < L->length, i++){if (e == L->base[i])return i + 1;}return 0; //如果元素不在循环里
}
05_在某个位置插入元素
Status SqlInsert(Sqlist *L, int position, SqlElemType *e){if (position < 1 || position > L->length + 1) return ERROR;if (L->length == SQLMAXSIZE)return OVERFLOW;for (int i = L->length - 1; i >= position - 1; i--){L->base[i+1] = L->base[i];}L->base[position - 1] = e;L->length ++;return OK;
}
06_删除某个位置上的元素
Status SqDelete(Sqlist *L, int position, SqlElemType *e){if (posiiton < 1 || position > L->length)return ERROR;for (int i = position ; i <= L->length - 1; i ++ ){L->base[i - 1] = L->base[i];}*e = L->base[position - 1];L->length --;return OK;
}
07_销毁线性表
Status SqDestory(Sqlist *L){if (!L->base) return ERROR;else{free(L->base); // free的输入参数是指针return OK;}
}
08_清空线性表
void SqClear(Sqlist *L){L->base = 0;
}
09_检查线性表是否为空
Status SqEmpty(Sqlist *L){if (0 == L->length) return TRUE;else return FALSE;
}