20003.数据结构C++ 顺序表

#include<iostream>
#define MaxSize 20

typedef int ElemType;

typedef struct {
	ElemType *elem;
	int length;
}SqList;


bool InitList(SqList& L) {
	/*
		初始化顺序表,分配空间。
	*/
	L.elem = new int [MaxSize];
	if (!L.elem)
		return false;
	L.length = 0;
	return true;
}

bool CreateList(SqList& L) {
	/*
		插入数据构建顺序表
	*/
	int x = 0, i = 0;
	while (x != -1){
		if (L.length == MaxSize) {
			std::cout  << "顺序表已经满了" << std::endl;
			return false;
		}
		std::cout << "请输入插入的元素" << std::endl;
		std::cin >> x;
		L.elem[i++] = x;
		L.length ++;

	}
	return true;
}

bool PrintList(SqList L) {
	/*
		打印顺序表中的内容。
	*/
	if (L.length == 0)
		return false;
	for (int i = 0; i < L.length; i++) {
		std::cout << L.elem[i] << std::endl;
	}
	return true;
}

bool GetElem(SqList L, int i, int& e) {
	// 从列表中取第i个值,并且返回到e中
	if (i<1 || i>L.length) {
		return false;
	}
	e = L.elem[i - 1];
	return true;
}

int LocateElem(SqList L, int e) {
	/*
		输入需要查找的元素,返回该元素所在的索引值。
	*/
	if (!L.elem)
		return false;
	for (int i = 1; i < L.length; i++)
		if (L.elem[i] == e)
			return i + 1;
	return -1;
}

bool ListInsert_Sq(SqList& L, int i, int e) {
	/*
		向顺序表中插入一个值。
	*/
	if (L.length == MaxSize)
		return false;
	for (int j = L.length; j > i; j--)
		L.elem[j] = L.elem[j - 1];
	L.elem[i] = e;
	L.length++;
	return true;
}

bool ListDelete_Sq(SqList& L, int i, int& e) {
	/*
		从顺序表中删除一个值。
	*/
	if (i<1 || i >L.length)
		return false;
	e = L.elem[i];
	for (int j = i; j < L.length; j++)
		L.elem[j] = L.elem[j + 1];
	L.length--;
	return true;
}

int main() {
	SqList L;

	// 初始化顺序表
	InitList(L);

	// 创建顺序表
	CreateList(L);

	// 打印顺序表
	PrintList(L);

	// 从表中取数
	int number;
	int e;
	std::cout << "输入您要查找的序号" << std::endl;
	std::cin >> number;
	GetElem(L, number, e);
	std::cout << e << std::endl;

	// 从顺序表中查找
	int index;
	int FindNumber;
	std::cout << "输入要查找的元素" << std::endl;
	std::cin >> FindNumber;
	index = LocateElem(L, FindNumber);
	if (index == -1)
		std::cout << "该顺序表中没有改元素" << std::endl;
	std::cout << index << std::endl;


	// 从顺序表中插入元素
	int InsertIndex;
	int InsertElem;
	std::cout << "请输入您要插入的元素的位置" << std::endl;
	std::cin >> InsertIndex;
	std::cout << "请输入您要出入的元素" << std::endl;
	std::cin >> InsertElem;
	ListInsert_Sq(L, InsertIndex, InsertElem);
	PrintList(L);

	// 从顺序表中删除一个元素
	int DeleteIndex;
	int DeleteElem;
	std::cout << "请输入您要删除元素的索引" << std::endl;
	std::cin >> DeleteIndex;
	DeleteElem = ListDelete_Sq(L, DeleteIndex, DeleteElem);
	std::cout << "删除的元素是" << DeleteElem << std::endl;
	return true;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魂•殿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值