线性表基本操作

本文介绍了数据结构中的线性表,详细讲解了线性表的基本操作,并提供了C++实现的接口设计与代码,同时附带了测试用例。更多相关资料可访问作者的个人网站。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据结构设计:

const int MAXSIZE = 20;//线性表大小

typedef int position;//设置别名代表的当前位置

struct LNode//结构体定义
{
	int Data[MAXSIZE];//线性表大小
	position last;//当前位置
};

typedef struct LNode* List;//用List代替struct LNode*

接口设计:

List makeEmpty() ;//初始化
position Find(int k, const List& L);//查询元素,返回元素位置
bool Insert(const List& L, int pos, int k);//在pos处插入k值
bool Delete(const List& L, int pos);//删除pos位置的元素
void Print(const List& L);//打印线性表

接口实现代码:

//初始化
List makeEmpty() {
	List L;
	L = (List)malloc(sizeof(struct LNode));//分配空间
	if (L) {//分配成功,设置数组长度的值
		L->last = -1;
	}
	return L;
}

//查找
position Find(int k, const List& L) {
	position i = 0;//从角标为0开始

	//超出数组长度或者匹配不成功则匹配下一位
	while (i <= L->last && L->Data[i] != k) {
		i++;
	}
	if (i > L->last) {
		return -1;//没找到,返回错误信息
	}
	else {
			return i;//返回位置信息
		}
}

//插入
bool Insert(const List& L, int pos, int k) {
	position i = pos;
	//MAXSIZE为总元素个数,当last=MAXSIZE-1时数组满
	if (L->last == MAXSIZE-1) {
		printf("线性表已满");
		return false;//无法插入返回
	}
	if (pos<0 || pos>MAXSIZE) {
		printf("插入位置不合法");
		return false;
	}
	for (int i = L->last;i >= pos;--i) {
		L->Data[i + 1] = L->Data[i];//向后顺位移动
	}
	L->Data[pos] = k;
	L->last++;
	return true;
}

//删除
bool Delete(const List& L, int pos) {
	if (pos<0 || pos>L->last) {
		printf("输入不合法");
		return false;
	}

	for (;pos + 1 < L->last;pos++) {
		L->Data[pos] = L->Data[pos + 1];
	}
	L->last--;
	return true;
}

//输出
void Print(const List& L) {
	for (int i = 0;i < L->last;++i) {
		cout << L->Data[i] << "   " << endl;
	}
}

测试代码:

//测试
int main() {
	struct LNode* list;
	list = makeEmpty();
	Insert(list, 0, 0);
	Insert(list, 1, 1);
	Insert(list, 2, 2);
	Insert(list, 3, 3);
	Insert(list, 4, 4);
	Insert(list, 5, 5);
	Print(list);
	int temp=Find(3, list);
	cout << temp << endl;
	Delete(list, 3);
	int temp1 = Find(3, list);
	cout << temp1 << endl;
	Print(list);
	delete list;
}

更多内容参见我的个人网站:http://www.huazhige.online/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值