数据结构之顺序表

构造一个空的顺序表

#define MAX_SIZE 100

typedef struct
{
	int *address;//基地址
	int length;//顺序表长度
	int size;//顺序表总空间
}LIST;

//创建一个空的顺序表
bool initList(LIST& list)
{
	list.address = new int[MAX_SIZE];
	if (!list.address) return false;

	list.length = 0;
	list.size = MAX_SIZE;
	return true;
}

  尾部添加数据

bool addPUSH(LIST& list,int data)
{
	if (list.length >= MAX_SIZE) return false;

	list.address[list.length] = data;
	list.length++;
	return true;
}

  范围内插入数据

bool ListInsert(LIST& list, int i, int data)
{
	if (i < 0 || i >= 100) return false;
	if (list.length == MAX_SIZE) return false;

	for (int j = list.length-1; j >= i; j--)
	{
		list.address[j + 1] = list.address[j];//从最后一个元素开始后移,直到第 i 个元 素后移
	}

	list.address[i] = data;//将新元素 e 放入第 i 个位置
	list.length++;//表加一
	return true;
}

  删除数据

bool Listdelete(LIST& list, int addr)
{
	if (addr<0 || addr>list.length) return false;

	if (addr == list.length - 1)
	{
		list.length--;
		return true;
	}

	for (int i = addr; i < list.length; i++)
	{
		list.address[i] = list.address[i +1];
	}
	list.length--;
	return true;
}

  顺序表销毁

bool destroyList(LIST& list)
{
	if (list.address) delete []list.address;
	list.length = 0;
	list.size = 0;
	return true;
}

  main函数

LIST list;

	cout << "初始化顺序表" << endl;
	if (initList(list))
	{
		cout << "顺序表初始化成功" << endl;
		
	}

	int count = 0;
	cout << "追加个数\t" ;
	cin >> count;
	int data = 0;
	for (int i = 0; i < count; i++)
	{
		cout << "参数:\t";
		cin >> data;
		cout<<endl;
		addPUSH(list, data);
	}
	listPrint(list);

	cout << "插入位置:\t" ;
	cin >> count;
		cout << "参数:\t";
		cin >> data;
		cout << endl;
		ListInsert(list, count, data);

		listPrint(list);
		
		cout << "所需删除的数据的地址:" ;
		cin >> data;
		if (Listdelete(list, data)) cout << "\t删除成功" << endl;
		else cout << "\t删除失败" << endl;
		listPrint(list);
cout << "顺序表销毁..." << endl;
		destroyList(list);
		listPrint(list);

 

	system("pause");

  编译环境VS2019

注:如有错误请与我联系,万分感谢!!!

数据结构之顺序表

上一篇:centos下按照chrome


下一篇:React 传参