已知长度为n的线性表A采用顺序存储结构,请写一个时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法可删除线性表中所有值为item的数据元素。
代码如下:
#include#include #define MAXSIZE 10 #define OK 1 #define ERROR 0 #define Free -1 typedef int Status; typedef int ElemType; struct Student { int id; }; typedef struct { Student* elem; int length; }SqList; //创建 Status Cj_List(SqList& L) { if (L.length >= 0) { printf("创建失败!原因:内存已被创建。an"); return ERROR; } L.elem = (Student*)malloc(MAXSIZE * sizeof(Student)); if (L.elem) { L.length = 0; return OK; } return ERROR; } //插入 Status Cr_List(SqList& L, int i, Student e) { if (L.length < 0) { printf("插入失败!原因:内存未被创建!an"); return ERROR; } if (L.length >= MAXSIZE) { printf("插入失败!原因:顺序表已满。an"); return ERROR; } if (i <= 0 || i > L.length + 1) { printf("插入位置不合法!an"); return ERROR; } for (int j = L.length - 1; j >= i - 1; j--) { L.elem[j + 1] = L.elem[j]; } L.elem[i - 1] = e; ++L.length; printf("插入成功!n当前顺序表长度为:%dn", L.length); return OK; } //查找item位置 Status Cz_List(SqList L, int item) { for (int i = 0; i < L.length; i++) { if (L.elem[i].id == item)return(i + 1); }return ERROR; } //删除某个位置元素 Status Sc_List(SqList& L, int i) { if (i == ERROR) { return ERROR; } for (i; i < L.length; i++) { L.elem[i - 1] = L.elem[i]; }--L.length; return OK; } //删除第一个item void Sci_List(SqList& L,int item) { Sc_List(L, Cz_List(L, item)); } //删除所有item void Wsci_List(SqList& L, int item) { int n = L.length; while (n>=1) { Sci_List(L, item); n--; } } //输出 Status print_List(SqList L) { if (L.length < 0) { printf("输出失败!原因:顺序表不存在。an"); return ERROR; } else { for (int i = 0; i < L.length; i++) { printf("%2d", L.elem[i].id); }printf("n"); return OK; } } int main() { SqList L; Student e; L.length = -1; int i,item,n=0; Cj_List(L); while (n != 5) { printf("输入插入的位置 数据(空格隔开)n"); scanf_s("%d %d", &i, &e.id); Cr_List(L, i, e); n++; } print_List( L); printf("输入要删除的item:"); scanf_s("%d",&item); printf("n"); Wsci_List(L, item); printf("删除完成!n"); print_List(L); printf("当前顺序表长度为:%dn", L.length); return 0; }
运行结果:
因为编译环境为 VS2019 有输入检测,如果scanf_s输入报错就把scanf_s改成scanf。



