顺序表代码

#include<iostream>
#include<string>
#include<cmath>
using namespace std;

#define MaxSize 100
#define OK 1
#define FLASE 0
#define OVER -1
typedef char Elemtype;
typedef int Status;

//顺序表类型
typedef struct 
{
	Elemtype* elem;
	int length;
}SqList;


//线性表L的初始化
Status InitList_Sq(SqList& L)
{
	L.elem = new Elemtype[MaxSize];
	if (!L.elem) exit(OVER);
	L.length = 0;
	return OK;
}

//销毁线性表L
void DestoryList(SqList& L)
{
	if (L.elem) delete L.elem;
}

//清空线性表
void ClearList(SqList& L)
{
	L.length = 0;
}

//求线性表L的长度
int GetLength(SqList L)
{
	return L.length;
}

//判断线性表是否为空
int isEmpty(SqList L)
{
	if (L.length == 0) return 1;
	else return 0;
}

//线性表的取值(根据位置求内容)
int GetElem(SqList L, int i, Elemtype& e)
{
	if (i<1 || i>L.length)return FLASE;
	e = L.elem[i - 1];
	return OK;
}

//查找该值e的位置
int LocateElem(SqList L, Elemtype e)
{
	int i;
	for (i = 0; i < L.length; i++)
	{
		if (L.elem[i] == e) return i + 1; 
		
	}
	return 0;
}

//显示列表
void ShowList(SqList L)
{
	for (int i = 0; i < L.length; i++)
		cout << L.elem[i] << " ";
	cout << endl;
}

//顺序表的插入
Status ListInsert(SqList& L, int i, Elemtype e)
{
	if (i<1 || i>L.length + 1) return OVER;
	if (L.length == MaxSize) return OVER;
	for (int j = L.length; j >= i - 1; j--)
	{
		L.elem[j + 1] = L.elem[j];
	}
	L.elem[i - 1] = e;
	L.length++;
	return OK;
}

//顺序表的删除
Status ListDelete(SqList& L, int i)
{
	if (i<1 || i>L.length) return OVER;
	for (int j = i; j <= L.length - 1; j++)
		L.elem[j - 1] = L.elem[j];
	L.length--;
	return OK;
}


int main()
{
	SqList L;
	InitList_Sq(L);   //L初始化
	cout << InitList_Sq(L)<< endl;
	if (isEmpty(L) == 1)  //判断是否为空
	{
		cout << "L为空!" << endl;
	}
	ListInsert(L, 1, 'a');  //添加数据
	ListInsert(L, 2, 'b');
	ListInsert(L, 3, 'c');
	ShowList(L);
	int Length = GetLength(L);
	cout << "长度为:" << Length << endl;
	char data; GetElem(L, 2, data); //求i=2的数据
	cout << data << endl;
	cout << LocateElem(L, 'c') << endl; //求数据 b 的位置
	cout << "数据长度为:" << GetLength(L)<<endl;
	ListDelete(L, 1);
	char data1; GetElem(L, 1, data1); //求i=1的数据
	cout << data1 << endl;
	ClearList(L);
	int Length1 = GetLength(L);
	cout << "长度为:" << Length1 << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值