栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言:顺序表删除item数据

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言:顺序表删除item数据

已知长度为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。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352378.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号