顺序表静态分配,数据元素类型为结构体
大学基础数据结构
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define Maxsize 10
typedef struct student {
int stu_num;
char stu_name[20];
}stu,ElemType;
typedef struct SqList_static {
ElemType data[Maxsize];
int len;
}SqList_static;
void InitSqList_static(SqList_static& L) {
for (int i = 0; i < Maxsize; i++) {
L.data[i].stu_num = 0;
strcpy(L.data[i].stu_name, "0");
}
L.len = 0;
}
void Print_SqList_static(SqList_static L) {
printf("\n");
for (int i = 0; i < L.len; i++) {
printf("%d ", L.data[i].stu_num);
printf("%s ", L.data[i].stu_name);
}
printf("\n");
}
bool SqList_static_Search_by_loc(SqList_static L, int i, ElemType& e) {
if (i<1 || i>L.len) return false;
e.stu_num = L.data[i - 1].stu_num;
strcpy(e.stu_name, L.data[i - 1].stu_name);
return true;
}
bool is_Elem_equal(ElemType a, ElemType b) {
if (a.stu_num == b.stu_num && 0 == strcmp(a.stu_name, b.stu_name))return true;
else return false;
}
void SqList_static_Search_by_val(SqList_static L, ElemType e, int a[]) {
for (int i = 0, j = 0; i < L.len; i++) {
if (is_Elem_equal(e, L.data[i])) {
a[j] = i + 1;
j++;
}
}
}
void a_value_to_b(ElemType &a, ElemType &b) {
b.stu_num = a.stu_num;
strcpy(b.stu_name, a.stu_name);
}
bool SqList_static_Insert(SqList_static& L, int i, ElemType& e) {
if (i<1 || i>L.len + 1)return false;
if (L.len >= Maxsize)return false;
for (int j = L.len; j >= i; j--) {
a_value_to_b(L.data[j - 1], L.data[j]);
}
a_value_to_b(e, L.data[i - 1]);
L.len++;
}
bool auto_SqList_static_Insert(SqList_static& L, ElemType e[], int num) {
if (num + L.len <= Maxsize) {
for (int k = 0; k < num; k++) {
SqList_static_Insert(L, L.len + 1, e[k]);
}
return true;
}
else return false;
}
bool SqList_delet(SqList_static& L, int i, ElemType& e) {
if (i<1 || i>L.len)return false;
a_value_to_b(L.data[i - 1], e);
for (int j = i; j < L.len; j++) {
a_value_to_b(L.data[j], L.data[j - 1]);
}
L.len--;
}
int main() {
SqList_static L;
InitSqList_static(L);
ElemType e[5] = { 1,"aaa",2,"bbb",3,"ccc",4,"ddd",5,"eee" };
if (auto_SqList_static_Insert(L, e, 5)) {
printf("添加成功,顺序表为:\n");
Print_SqList_static(L);
}
if (auto_SqList_static_Insert(L, e, 5)) {
printf("添加成功,顺序表为:\n");
Print_SqList_static(L);
}
ElemType ret;
if(SqList_static_Search_by_loc(L, 3, ret)){
printf("按照位置查找成功");
printf("%d %s\n", ret.stu_num,ret.stu_name);
}
int a[Maxsize] = { -1 };
ElemType val_for_search = { 2,"bbb" };
SqList_static_Search_by_val(L, val_for_search, a);
printf("查找到的位序数组为:");
for (int i = 0; i < Maxsize; i++) {
printf("%d", a[i]);
}
ElemType delet[Maxsize] = {-1};
if (SqList_delet(L, 1, delet[0])) {
printf("删除成功,删除后顺序表为:");
Print_SqList_static(L);
}else printf("删除失败");
}