顺序表之C语言实现

本文介绍了如何使用C语言实现顺序表。通过分析ArrayList.h、ArrayList.cpp和源.cpp文件,展示了顺序表的创建、插入、删除等操作的具体实现过程,并给出了运行结果。

//ArrayList.h文件

const int MaxSize = 50;
template<class T>   //定义模板类ArrayList
class ArrayList{
	public:
		ArrayList() { length = 0 }; //无参构造函数
		
		ArrayList(T a[], int n);  //有参构造函数
		~ArrayList() {};
		void PrintList();
		bool InsertList(int i, T a);
		bool DeleteList(int i, T *a);
		int Length();
		int GetList(T x);
		T GetNum(int i);
	private:
		int length; //线性表的长度
		T data[MaxSize]; //存放线性表的数组
};

//ArrayList.cpp文件

#include"ArrayList.h"
template<class T>
ArrayList<T>::ArrayList(T a[], int n)
{
	if (n > MaxSize)
	throw("参数非法");
	for (int i = 0; i < n; i++)
	{
		data[i] = a[i];
	}
	length = n;
	}
	template<class T>
	bool ArrayList<T>::DeleteList(int i, T *x)
	{
		if (i>length || i<1)
		throw("参数非法");
		else
		{
		*x = data[i - 1];
		for (int j = i; j < length; j++)
	{
		data[j - 1] = data[j];
	}
	length--;
	return true;
	}
	}
	template<class T>
	int ArrayList<T>::GetList(T a)
	{
	for (int i = 0; i < length; i++)
	{
	if (a == data[i])
	{
	return i + 1;
	}
	}
	return -1;
	}
	template<class T>
	T ArrayList<T>::GetNum(int x)
	{
	if (x > length || x < 1)
	{
	throw "查找位置非法";
	}
	else
	return data[x - 1];
	}
	template<class T>
	bool ArrayList<T>::InsertList(int i, T a)
	{
	if (i > length + 1 || i < 1)
	{
	throw("参数错误");
	}
	else
	{
	for (int j = length; j >= i; j--)
	{
	data[j] = data[j - 1];
	}
	data[i - 1] = a;
	length++;
	}
	}
	template<class T>
	int ArrayList<T>::Length()
	{
	return length;
	}
	template<class T>
	void ArrayList<T>::PrintList()
	{
	for (int i = 0; i < length; i++)
	{
cout << data[i] << endl;
}
}

//源.cpp文件

#include<iostream>
#include<string>
using namespace std;
#include"ArrayList.cpp"
int main(void)
{
string a[5] = {"大明","二明","三明","四明","五明"};
ArrayList<string> x(a,5);
cout << "分别是:" << endl;
x.PrintList();
cout <<"总共人数:"<< x.Length() << endl;
cout<<"小明的位置是:"<<x.GetList("小明")<<endl;
cout<<"第三个位置的学生是:"<<x.GetNum(3)<<endl;
x.InsertList(6, "小明");
cout << "插入操作:" << endl;
x.PrintList();
string b;
x.DeleteList(2,&b);
cout << "删除操作:" <<"(删除的学生姓名是"<<b<<")"<< endl;
x.PrintList();
x.~ArrayList();
system("pause");
return 0;
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值