<span style="font-size:24px;">順序表(C++語言實現)
</span>
<span style="font-size:24px;">含有頭插尾插、頭刪尾刪、插入、修改、刪除、查找等功能</span>
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
typedef int DataType;
typedef struct FindRet
{
bool isFind;
size_t index;
}FindRet;
class SeqList
{
public:
SeqList()//構造函數
:_array(NULL)
, _size(0)
, _capacity(0)
{}
SeqList(const SeqList& sList)//拷貝構造函數
{
_array = new DataType[sList._capacity];
memcpy(_array, sList._array, sizeof(DataType)*sList._size);
}
SeqList& operator=(const SeqList& sList)//賦值運算符的重載
{
}
~SeqList()
{
if (_array)
{
delete[] _array;
}
_size = 0;
_capacity = 0;
}
public:
void PushBack(const DataType& x)
{
_CheckCapacity();
_array[_size++] = x;
}
void PopBack()
{
if (_size)
--_size;
}
void PushFront(const DataType& x)
{
_CheckCapacity();
size_t i = _size;
for (; i > 0; i--)
{
_array[i] = _array[i-1];
}
_array[0] = x;
_size++;
}
void PopFront()
{
if (_size)
{
int i = 0;
for (; i < _size; i++)
{
_array[i] = _array[i + 1];
}
--_size;
}
}
void DisPlay()
{
size_t i = 0;
for ( ; i < _size; ++i)
{
cout << _array[i] << "->" ;
}
cout << endl;
}
void Insert(size_t index, const DataType& x )
{
_CheckCapacity();
size_t i = _size;
for (; 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 (; index < _size; index++)
{
_array[index] = _array[index + 1];
}
--_size;
}
FindRet Find(SeqList* pSeq, const DataType& x, size_t index)
{
FindRet ret;
for (; index < _size; index++)
{
if (x == _array[index])
{
ret.isFind = true;
ret.index = index;
cout << "is Find." << endl;
return ret;
}
ret.isFind = false;
cout << "isn't Find." << endl;
return ret;
}
}
private:
DataType* _array;
size_t _size;
size_t _capacity;
private:
void _CheckCapacity()
{
if (_size == _capacity)
{
_capacity = 2 * _capacity + 3;
DataType* tmp = new DataType[_capacity];
memcpy(tmp,_array,sizeof(DataType)*_size);
delete[] _array;
_array = tmp;
}
}
};
void Test1()
{
SeqList s1;
s1.PushBack(1);
s1.PushBack(2);
s1.PushBack(3);
s1.PushBack(4);
s1.PushBack(5);
s1.PushBack(6);
s1.DisPlay();
s1.PopBack();
s1.PopBack();
s1.PopBack();
s1.DisPlay();
}
void Test2()
{
SeqList s2;
s2.PushFront(1);
s2.PushFront(2);
s2.PushFront(3);
s2.PushFront(4);
s2.PushFront(5);
s2.PushFront(6);
s2.DisPlay();
s2.PopFront();
s2.PopFront();
s2.PopFront();
s2.DisPlay();
}
void Test3()
{
SeqList s3;
s3.PushBack(1);
s3.PushBack(2);
s3.PushBack(3);
s3.PushBack(4);
s3.PushBack(5);
s3.PushBack(6);
s3.DisPlay();
s3.Modified(2, 8);
s3.DisPlay();
s3.Find(&s3, 1, 0);
s3.Remove(1);
s3.DisPlay();
s3.Insert(5, 9);
s3.DisPlay();
}
int main()
{
Test1();
Test2();
Test3();
system("pause");
return 0;
}