数据结构实验--------线性表的实现

   使用的教材是电子工业出版社出版的《Data Structures and Algorithm Analysis in C++  》(《数据结构与算法分析(C++)》(第三版)),作者是【美】Clifford A Shaffer,译者是张铭、刘晓丹等。所以,有些代码与书上给出来的几近相同,如有侵权,请联系本人([email protected]),我会删除文章的。

        

       ----ListADT.h-------

#ifndef LIST
#define LIST

template<typename E> class List
{
private :
	void operator = (const List& ){}
	List (const List&){}
public :
	List() {}
	virtual ~List() {}
	virtual void clear() = 0;
	virtual void insert(const E& item ) = 0;
	virtual void append(const E& item ) = 0;
	virtual E remove() = 0;
	virtual void moveToStart() = 0;
	virtual void moveToEnd() = 0;
	virtual void prev() = 0;
	virtual void next() = 0 ;
	virtual int length() const = 0;
	virtual int currPos() const = 0;
	virtual void moveToPos(int pos) = 0;
	virtual const E& getValue() const = 0;
};

template<typename E>
class Alist:public List<E>
{
private :
	int listSize;
	int maxSize;
	int curr;
	E* listArray;
public :
	Alist (int size=50)
	{
		maxSize = size;
		listSize = curr = 0;
		listArray = new E[maxSize];
	}
	~Alist() { delete[] listArray; }

	void clear()
	{
		delete [] listArray;
		listSize = curr =0;
		listArray = new E[maxSize];
	}

	void insert(const E& item)
	{
		if(listSize>=maxSize)
			return;
		for(int i=listSize;i>curr;i--)
		{
			listArray[i] = listArray[i-1];
		}
		listArray[curr] = item;
		listSize++;
	}

	void append(const E&item)
	{
		if(listSize>=maxSize)
			return;
		listArray[listSize++] = item;
	}

	E remove()
	{
		E temp = listArray[curr];
		listSize--;
		for(int i=curr;i<listSize;i++)
		{
			listArray[i] = listArray[i+1];
		}
		return temp;
	}

	void moveToStart()
	{
		curr = 0;
	}

	void moveToEnd()
	{
		curr = listSize-1;
	}

	void prev()
	{
		if(curr==0)
			return;
		curr--;
	}

	void next()
	{
		if(curr==listSize-1)
			return ;
		curr++;
	}

	int length() const
	{
		return listSize;
	}

	int currPos() const
	{
		return curr;
	}

	void moveToPos(int pos)
	{
		if(pos>=listSize)
			return;
		curr = pos;
	}

	const E& getValue() const
	{
		return listArray[curr];
	}
};
#endif

----Main.cpp----

#include"ListADT.h"
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

template<typename E> void print(Alist<E>& arrayList)
{
	arrayList.moveToStart();
	while(arrayList.currPos()<arrayList.length()-1)
	{
		cout<<arrayList.getValue()<<"  ";
		arrayList.next();
	}
	cout<<arrayList.getValue()<<endl;
}

int main()
{
	srand(int(time(0)));
	Alist<int> arrayList;
	cout<<"Input data are :"<<endl;
	for(int i=0;i<10;i++)
	{
		int temp = rand()/200;
		arrayList.append(temp);
	}
	print(arrayList);
	cout<<"\nInsert 99 to the position 6th"<<endl;
	arrayList.moveToPos(5);
	arrayList.insert(99);
	print(arrayList);
	cout<<"\nRemove the value on the position 3rd."<<endl;
	arrayList.moveToPos(2);
	arrayList.remove();
	print(arrayList);
	cout<<"\nAppend 999 ."<<endl;
	arrayList.append(999);
	print(arrayList);
	system("PAUSE");
}


运行截图:

数据结构实验--------线性表的实现_第1张图片

你可能感兴趣的:(数据结构,线性表)