代码实现:
#include <stdlib.h>
typedef int DataType;
class SeqList
{
public:
////传统写法
SeqList()
:_arr( NULL), _size(0), _capacity(0)
{
}
//现代写法
/*SeqList(DataType* arr, size_t size)
:_arr (new DataType[size])
, _size(size)
, _capacity(size)
{
memcpy(_arr, arr, _size*sizeof(DataType));
}*/
////传统写法
SeqList( const SeqList &s)
:_arr( new DataType [s._size])
, _size( s._size)
, _capacity( s._size)
{
memcpy(_arr, s._arr, sizeof (DataType)*_size);
}
//现代写法
/*SeqList(const SeqList &s)
:_arr(NULL)
{
SeqList temp(s._arr, s._size);
swap(_arr, temp._arr);
_size = s._size;
_capacity = s._capacity;
}*/
//传统写法
SeqList& operator=(const SeqList & s)
{
if (this != &s)
{
DataType *temp = new DataType[ s._size];
delete[] _arr;
_arr = s._arr;
_size = s._size;
_capacity = s._size;
memcpy(_arr, s._arr, sizeof(DataType )*_size);
}
return *this ;
}
//现代写法
/*SeqList& operator=(SeqList s)
{
swap(s._arr, _arr);
_size = s._size;
_capacity = s._capacity;
return *this;
}*/
~SeqList()
{
if (_arr)
{
delete[] _arr;
}
}
public:
void pushBack(DataType x)
{
_Checkcapacity();
_arr[_size++] = x;
}
void popBack()
{
if (_size <= 0)
{
return;
}
else
{
_size--;
}
}
void pushFront(DataType x)
{
_Checkcapacity();
for (int begin = _size; begin >= 0; begin--)
{
_arr[begin + 1] = _arr[begin];
}
_arr[0] = x;
_size++;
}
void popFront()
{
if (_size <= 0)
{
return;
}
for (int begin = 0; begin < _size; begin++)
{
_arr[begin] = _arr[begin + 1];
}
_size--;
}
void Insert(size_t pos, DataType x )
{
_Checkcapacity();
int begin = pos ;
for (begin = _size; begin >= pos ; begin++)
{
_arr[begin + 1] = _arr[begin];
}
_arr[ pos] = x ;
_size++;
}
void Erase(size_t pos)
{
if (_size <= 0)
{
return;
}
int begin = pos ;
for (begin = pos ; begin < _size; begin++)
{
_arr[begin] = _arr[begin + 1];
}
_size--;
}
int Find(DataType x)
{
for (int i = 0; i < _size; i++)
{
if (_arr[i] == x )
{
return i;
}
}
return -1;
}
void PrintfSeqList()
{
for (int i = 0; i < _size; i++)
{
cout << _arr[i] << " " ;
}
cout << endl;
}
private:
void _Checkcapacity()
{
if (_size>=_capacity)
{
_capacity = 2 * _capacity + 3;
_arr = ( DataType*)realloc(_arr, _capacity*sizeof(DataType ));
}
}
private:
DataType *_arr;
size_t _size;
size_t _capacity;
};