线性表的顺序存储表示和实现

线性表的顺序表示:指的是用一组地址连续的存储单元依次存储线性表的数据元素,通常称这种存储结构的线性表为顺序表;
特点:逻辑和物理次序都相;
线性表的顺序存储结构是一种随机存取的存储结构即只要确定了存储线性表的起始位置,线性表的任一数据元素都可以随机存取;
作为一个初学者,出错是难免的,还请各位大佬指正;

#include
#include
#include
using namespace std;

#define MAXSIZE 100
#define ERROR 1
#define OK 0

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

int InitList(SqList &L);
int LocateElem(SqList L,int i);
int ListInsert(SqList &L, int i ,int e);
int ListDelete(SqList &L,int i);

int main()
{
	SqList L;
	int length, flag, i, e;
	InitList(L);
	cout << "请输入顺序表的长度"<< endl;
	cin >> length;
	if (length <= MAXSIZE)
	{
		for (int i = 0; i < length; i++)
		{
			cin >> L.elem[i];
			L.length++;
		}
		cout << "线性表的数值为" << endl;
		for (int i = 0; i < L.length; i++)
		{
			cout << L.elem[i] << " ";
		}
	}
	else
	{
		cout << "输入的长度大于线性表的长度" << endl;
	}
	cout << "请输入你想进行的操作" << endl;
	cout << "1,查找;2,插入;3,删除;" << endl;
	cin >> flag;
	switch (flag)
	{
	case 1:
		cout << "请输入要查找的位置" << endl;
		cin >> i;
		LocateElem(L, i);
		break;
	case 2:
		cout << "请输入要插入的位置" << endl;
		cin >> i;
		cout << "请输入要插入的数" << endl;
		cin >> e;
		ListInsert(L, i, e);
		break;
	case 3:
		cout << "请输入要删除的位置" << endl;
		cin >> i;
		ListDelete(L,i);
		break;
	default:
		cout << "输入不正确"<<endl;
		break;
	}
	system("pause");
}
//初始化顺序表
int InitList(SqList &L)
{
	L.elem = new int[MAXSIZE];
	if (!L.elem)		//检查数组是否获取成功
		exit(ERROR);
	L.length = 0;
	return OK;
}
//顺序表的查找
int LocateElem(SqList L, int i)
{
	if (i<1||i>L.length)
	{
		cout << "你输入的数值错误" << endl;
		return ERROR;
	}
	cout << L.elem[i-1] << endl;
	return OK;
}
//顺序表的插入
int ListInsert(SqList &L, int i, int e)
{
	if (i<1 || i>L.length)
		return ERROR;
	if (L.length == MAXSIZE)
		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++;
	return OK;
}
//顺序表的删除
int ListDelete(SqList &L, int i)
{
	if (i<1 || i>L.length)
	{
		cout << "输入的数值错误" << endl;
		return ERROR;
	}
	for (int j = i; j < L.length - 1; j++)
		L.elem[j - 1] = L.elem[j];
	L.length--;
	return OK;
}

你可能感兴趣的:(学习C语言)