关闭

线性表顺序存储结构的C++模板类程序源代码

标签: 线性表顺序存储结构C++源代码
362人阅读 评论(0) 收藏 举报

线性表顺序存储结构说白了就是数组,类定义了两个成员变量:一个足够大的数组和元素个数变量。下面是自己写的一个线性表类,可以直接使用或增加成员函数使用。

#ifndef LINEARLIST_H
#define LINEARLIST_H
#include <iostream>
const int MAXSIZE=100;
template<typename ElementType>
class LinearList
{
	private:
		ElementType Data[MAXSIZE];
		int last;
	public:
		LinearList();
		~LinearList(){
		}
		int Find(ElementType);
		void Insert(int ,ElementType);
		void Delete(int);		
		bool IsEmpty();
		bool IsFull();
		void Print();
		ElementType operator[](int);
};


template<typename ElementType>
LinearList<ElementType>::LinearList():last(-1)
{
}
template<typename ElementType>
int LinearList<ElementType>::Find(ElementType x)
{
	for(int i=0;i<=last;i++)
	{
		if(Data[i]==x)
		{
			std::cout<<"We find the element "<<x<<" that you search, it is at NO." <<i<<" position !"<<std::endl;
			return i;
		}		
	}
	std::cout<<"We did not find the element that you search!"<<std::endl;
	return -1;
}
template<typename ElementType>
void LinearList<ElementType>::Insert(int i ,ElementType x)
{
	if(IsFull())
	{
		std::cout<<"The List is full now!";
		return;
	}	
	for(int j=last;j>=i;j--)
	{
		Data[j+1]=Data[j];
	}
	Data[i]=x;
	last++;
	return;
}
template<typename ElementType>
void LinearList<ElementType>::Delete(int i)
{
	if(IsEmpty())
	{
		std::cout<<"The List is empty now!"<<std::endl;
		return;
	}
	if(i>last+1)
	{
		std::cout<<"The element you delete is out of the list!"<<std::endl;
		return;
	}
	for(int j=i;j<last;j++)
	{
		Data[j]=Data[j+1];
	}
	last--;
	return;	
}		
template<typename ElementType>
bool LinearList<ElementType>::IsEmpty()
{
	if(last==-1)
		return true;
	else
		return false;
}
template<typename ElementType>
bool LinearList<ElementType>::IsFull()
{
	if(last==MAXSIZE)
		return true;
	else 
		return false;
}
template<typename ElementType>
void LinearList<ElementType>::Print()
{
	std::cout<<"The list is printed in the next:\n";
	for(int i=0;i<=last;i++)
	{
		std::cout<<Data[i]<<" ";
	}
	std::cout<<std::endl;
}
template<typename ElementType>
ElementType LinearList<ElementType>::operator[](int i)
{
	return Data[i];
}
#endif


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:38286次
    • 积分:1228
    • 等级:
    • 排名:千里之外
    • 原创:72篇
    • 转载:38篇
    • 译文:0篇
    • 评论:0条