顺序表动态存储
有问题欢迎提出,评论区一起讨论
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define _CRT_SECURE_NO_WARNINGS
#define InitSize 10
typedef int ElemType;
typedef struct {
ElemType* data;
int length,MaxSize;
}SqList;
//初始化表
void InitList(SqList&);
//输出操作
void PrintList(SqList);
//求表长
int Length(SqList);
//判空操作
bool Empty(SqList);
//插入操作,第二个形参表示线性表位序,从1开始
bool ListInsert(SqList&, int, ElemType);
//删除操作,第二个形参表示线性表位序;第三个形参表示删除的元素
bool ListDelete(SqList&, int, ElemType&);
//按位查找操纵,第二个形参表示线性表位序
ElemType GetElem(SqList, int);
//按值查找操作,返回该值位序
int LocateElem(SqList, ElemType);
//扩容线性表
void IncreaseSize(SqList &);
int main(void) {
SqList L;
InitList(L);
for (int i = 1; i <= 50; i++) {
ListInsert(L, i, i);
}
ListInsert(L, 7, 100);
ElemType e;
ListDelete(L, 7, e);
printf("%d\n", e);
PrintList(L);
return 0;
}
void InitList(SqList& L) {
L.data = (ElemType*)malloc(sizeof(ElemType) * InitSize);
if (NULL == L.data) {
printf("系统分配内存失败!\n");
exit(0);
}
L.length = 0;
L.MaxSize = InitSize;
}
void PrintList(SqList L) {
int length = Length(L);
if (length == 0) {
printf("空表!\n");
}
for (int i = 0; i < length; i++) {
printf("%d\t", L.data[i]);
}
}
int Length(SqList L) {
return L.length;
}
bool Empty(SqList L) {
return L.length == 0 ? true : false;
}
bool ListInsert(SqList& L, int i, ElemType e) {
int length = Length(L);
if (length == L.MaxSize) {
IncreaseSize(L);
}
if (i < 1 || i> length + 1) {
printf("请输入正确的位序!\n");
return false;
}
for (int j = 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) {
int length = Length(L);
if (length == 0) {
printf("空表!\n");
return false;
}
if (i < 1 || i > length) {
printf("请输入正确的位序!\n");
return false;
}
e = L.data[i - 1];
for (int j = i; j < length; j++) {
L.data[j - 1] = L.data[j];
}
L.length--;
return true;
}
ElemType GetElem(SqList L, int i) {
int length = Length(L);
if (length == 0) {
printf("空表!\n");
exit(0);
}
if (i < 1 || i > length) {
printf("请输入正确的位序!\n");
exit(0);
}
return L.data[i - 1];
}
int LocateElem(SqList L, ElemType e) {
int length = Length(L);
if (length == 0) {
printf("空表!\n");
return -1;
}
for (int i = 0; i < length; i++) {
if (L.data[i] == e) {
return i + 1;
}
}
return -1;
}
void IncreaseSize(SqList& L) {
int* data = L.data;
L.data = (ElemType*)malloc(sizeof(ElemType) * (L.MaxSize + (L.MaxSize >> 1)));
if (NULL == L.data) {
printf("系统分配内存失败!\n");
exit(0);
}
for (int i = 0; i < L.length; i++) {
L.data[i] = data[i];
}
L.MaxSize += L.MaxSize >> 1;
}