c++实现顺序表

来源:互联网 发布:雨露计划app软件 编辑:程序博客网 时间:2024/06/05 15:57
//顺序表就是动态增长的数组#include<iostream>#include<assert.h>using namespace std;typedef int DataType;class SeqList{public:    SeqList()//构造        :_array(NULL)        , _size(0)        , _capacity(0)    {}    SeqList(const SeqList& s)//拷贝构造    {        _array = (DataType*)malloc(sizeof(DataType)*s._size);        memcpy(_array, s._array, sizeof(DataType)*s._size);        _size = _capacity = s._size;    }    ~SeqList()//析构    {        if (_array)        {            free(_array);            _size = _capacity = 0;            _array = NULL;        }    }    SeqList& operator=(SeqList s)    {        Swap(s);        return *this;    }    void Swap(SeqList& s)    {        swap(_array, s._array);        swap(_size, s._size);        swap(_capacity, s._capacity);    }    void PushBack(DataType x)//尾插    {        CheckCapacity();        _array[_size++] = x;    }    void PopBack()//尾删    {        Erase(_size - 1);    }    void PushFront(DataType x)//头插    {        CheckCapacity();        Insert(0, x);    }    void PopFront()//头删    {        Erase(0);    }    void Insert(size_t pos, DataType x)    {        assert(pos <= _size);        CheckCapacity();//检查,扩容        for (int end = _size-1; end >=(int) pos; --end)        {            _array[end + 1] = _array[end];        }        _array[pos] = x;        ++_size;    }    void Erase(size_t pos)    {        assert(pos <= _size - 1);        for (int end = _size - 1;(int) pos <= end;++pos)        {            _array[pos] = _array[pos + 1];        }        --_size;    }    DataType& operator[](size_t pos)    {        assert(pos);        return _array[pos];    }    void Print()//打印    {        int i = 0;        while (i<=int(_size-1))        {            cout << _array[i] << " ";            ++i;        }    }    void CheckCapacity()    {        if (_size == _capacity)//相等,容量满了,就要增容        {            _capacity =_capacity*2+3;            _array = (DataType*)realloc(_array, _capacity*sizeof(DataType));        }    }private:    DataType* _array;//指针数组    size_t _size;//有效数据的个数    size_t _capacity;//容量};void TestSeqList(){    SeqList s1;    s1.PushBack(1);    s1.PushBack(2);    s1.PushBack(3);    s1.PushBack(4);    //s1.Erase(0);    s1.PopBack();    s1.PopFront();    s1.Print();}
原创粉丝点击