C++实现顺序表

#include<iostream>
using namespace std;

typedef struct FindRet
{
	bool isFind;//是否找到的标示
	size_t index;//找到数据的下标
}Findret;

typedef int DataType;
class SeqList
{
public:
	SeqList()
	    :_array(NULL)
	    ,_size(0)
            ,_capicity(0)
	{}
        SeqList(const SeqList& sList)
	{
		_array = new DataType [sList._capicity];
		memcpy(_array, sList._array,sizeof(DataType)* sList._size);
		_size = sList._size;
		_capicity = sList._capicity;

	}
        SeqList& operator=(const SeqList& sList)
	{
		if(this != & sList)
		{
			DataType* tmp = new DataType [sList._capicity];
			memcpy(tmp, sList._array,sizeof(DataType)* sList._size);
			delete[] _array;
			_array = tmp;
			_size = sList._size;
		    _capicity = sList._capicity;

		}
		return *this;
	}
	~SeqList()
	{
		if(_array)
		{
			delete[] _array;
		}
		_size=0;
		_capicity=0;
	}
public:
	void Print()
	{
		for(size_t i=0;i<_size;++i)
		{
			cout<<_array[i]<<" ";
		}
		cout<<endl;
	}
	void PushBack(const DataType &x)//从尾部插
	{
		_CheckCapicity();
		_array[_size++]=x;
	}
        void PopBack()//从尾部删
	{
		if(_size)
		{
			--_size;
		}
	}

    void PushFront(const DataType& x)//从头部插
	{
		_CheckCapicity();
        for(int i=_size;i>0;--i)
		{
			_array[i]=_array[i-1];
		}
		_array[0]=x;
		++_size;
	}
    void PopFront()//从头部删
	{
		if(_size)
		{
			for(int i=0;i<_size-1;++i)
			{
				_array[i]=_array[i+1];
			}
			--_size;
		}
	}

	void Insert(size_t index,const DataType& x)//插入到index
	{
		_CheckCapicity(); 
		for(size_t i = _size;i > index;--i)
		{
			_array[i] = _array[i - 1];
		}
		_array[index] = x;
		++_size;
	}
    void Modified (size_t index,const DataType& x )
	{
		_array[index] = x;
	}
	void Remove(size_t index)
	{
		for(size_t i= index;i < _size-1;i++)
		{
			_array[i] = _array[i + 1];
		}
		-- _size;
	}
	bool Find(const DataType& x, size_t index)
	{
		for(size_t i = 0;i < _size-1;i++)
		{
			if(_array[i] == x)
			return true;
		}
		return false;
	}
private:
	void _CheckCapicity()
	{
		if(_size==_capicity)
		{
			_capicity=2*_capicity+3;
			DataType* tmp=new DataType[_capicity];
			memcpy(tmp,_array,sizeof(DataType)*_size);
			delete[] _array;
			_array=tmp;
		}	
	}
private:
	DataType* _array;
	size_t _size;//当前的有效数据个数
    size_t _capicity;//容量
};
int main()
{
    SeqList s1;
	s1.PushBack(1);
	s1.PushBack(2);
    s1.PushBack(3);
    s1.PushBack(4);
	s1.Print();

	s1.PopBack();
	s1.Print();

    s1.PushFront(0);
	s1.Print();

	s1.PopFront();
	s1.PopFront();
	s1.Print();

	s1.Insert(0,5);
	s1.Print();

	s1.Remove(0);
	s1.Print();

    SeqList s2;
	s2=s1;
	s2.Print();

	SeqList s3(s1);
	s3.Print();


	return 0;
}

你可能感兴趣的:(C++实现顺序表)