WEB开发网
开发学院软件开发C++ 线性表之顺序表 阅读

线性表之顺序表

 2012-05-24 15:28:09 来源:WEB开发网   
核心提示:#include<iostream>using namespace std;template <typename T>class List{private:T *data;int length;int listsize;public:List(int k=1){data=new T[k];len
#include<iostream>
using namespace std;
template <typename T>class List{
private:
	T *data;
	int length;
	int listsize;
public:
	List(int k=1)
	{
		data=new T[k];
		length=0;
		listsize=k;
	}
	~List()
	{
		delete[]data;
	}
	void clearList()
	{
		length=0;
	}
	bool empty()
	{
		return length==0;
	}
	int getLength()
	{
		return length;
	}
	bool getElem(int i,T &e)
	{
		if(i<1 || i>length)
		{
			return false;
		}
		e=*(data+i-1);
		return 0;
	}
	bool InsertList(int i,T e)
	{
		T *base;
		if(i<0 || i>length+1)
		{
			return false;
		}
		if(length==listsize)
		{
			base=new T[listsize*2];
			for(int i=0;i<length;i++)
			{
				*(base+i)=*(data+i);
			}
			delete []data;
			data=base;
			listsize*=2;
		}
		for(int j=length-1;j>=i-1;j--)
		{
			*(data+j+1)=*(data+j);
		}
		*(data+i-1)=e;
		length++;
		return true;
	}
	bool deleteList(int i,T &e)
	{
		if(i<1 || i>length)
		{
			return false;
		}
		e=*(data+i-1);
		for(int j=i;j<length;j++)
		{
			*(data+j-1)=*(data+j);
		}
		length--;
		return true;
	}
	void print()
	{
		for(int i=0;i<length;i++)
		{
			cout<<*(data+i)<<" ";
		}
		cout<<endl;
	}
	template<class T>
	friend void MergeList(List <T>&,List <T>&,List <T> &);
	template <class T>
	friend ostream & operator <<(ostream &,List <T> &);
};
template<class T>
void MergeList(List <T>&a,List <T>&b,List <T> &c)
{
	int e,i=0,j=0,k=0;
	while(i<a.length && j<b.length)
	{
		if(a.data[i]<=b.data[j])
		{
			a.getElem (++i,e);
			c.InsertList (++k,e);
		}
		else {
			b.getElem (++j,e);
			c.InsertList(++k,e);
		}
	}
	while(i<a.length)
	{
		a.getElem (++i,e);
		c.InsertList (++k,e);
	}
	while(j<b.length )
	{
		b.getElem(++j,e);
			c.InsertList (++k,e);
	}
}
	template <class T>
ostream & operator <<(ostream & out,List <T> & a)
	{
		for(int i=0;i<a.length;i++)
		{
			out<<a.data[i]<<" ";
		}
		return out;
	}
int main()
{
	List<int> La,Lb,Lc;
	cout<<"La是否为空?"<<boolalpha<<La.empty ();
	for(int i=0;i<5;i++)
		La.InsertList (i+1,i*2);
	for(int i=0;i<6;i++)
		Lb.InsertList(i+1,i*3);
	cout<<"La的各个元素是:"<<La;
	cout<<"Lb的各个元素是:"<<Lb;
	MergeList(La,Lb,Lc);
	cout<<"Lc的各个元素是:"<<Lc
	return 0;
}

Tags:线性 顺序

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接