《大话数据结构》C++实现线性表的顺序存储及插入和删除操作

本代码中L.length赋值是7,可以修改L.length的值来改变终端输入数字的个数。

#include
#include"stdio.h"

using namespace std;

constexpr auto MAXSIZE = 20;
constexpr auto OK = 1;
constexpr auto ERROR = 0;
constexpr auto TRUE = 1;
constexpr auto FALSE = 0;

typedef int ElemType;
typedef int Status;

typedef struct
{
	ElemType data[MAXSIZE];
	int length;
}SqList;

Status ListInsert(SqList *L,int i,ElemType e);
Status ListDelete(SqList *L,int i,ElemType e);

//获取线性表元素的操作
Status GetElem(SqList L,int i,ElemType *e)
{
	if (L.length==0 || i<=0 || i>L.length)
	{
		return ERROR;
	}
	*e = L.data[i-1];
	return OK;
}

//在L中第i个位置插入元素e的函数(第i个位置不是数组中的下标,是一个个数过去的i个数字)
Status ListInsert(SqList* L, int i, ElemType e)
{
	if (L->length==MAXSIZE)
	{
		return ERROR;
	}
	if (i<1 || i>L->length+1)
	{
		return ERROR;
	}
	if (i<=L->length)
	{
		for (int k = L->length-1; k >= i-1; k--)
		{
			L->data[k + 1] = L->data[k];
		}
	}
	L->data[i - 1] = e;
	L->length++;
	return OK;
}

//删除L中的第i个数据元素,并用e返回其值,L的长度减1
Status ListDelete(SqList* L, int i, ElemType e)
{
	if (L->length==0)
	{
		return ERROR;
	}
	if (i<1 || i>L->length)
	{
		return ERROR;
	}
	e = L->data[i-1];
	if (ilength)
	{
		for (int k = i; k < L->length; k++)
		{
			L->data[k - 1] = L->data[k];
		}
	}
	L->length--;
	return OK;
}

int main()
{
	SqList L;
	L.length = 7;
	cout << "请输入" << L.length << "个数字:" << endl;
	for ( int i = 0;  i <= L.length -1 ; i++)
	{
		cin >> L.data[i];
	}

	ListInsert(&L,4,9);

	cout << "插入数字后的结果是:" << endl;
	for (int i = 0; i <= L.length -1; i++)
	{
		cout << L.data[i] << " ";
	}
	cout << endl;

	ListDelete(&L, 4, 9);
	cout << "删除数字后的结果是:" << endl;
	for (int i = 0; i <= L.length - 1; i++)
	{
		cout << L.data[i] << " ";
	}
	cout << endl;

	return 0;
}

 

你可能感兴趣的:(C++算法编程)