顺序表的简单实现

#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& operator=(const SeqList& s)
    {
        if (this != &s)
        {
            free(_array);
            _array = (DataType*)malloc(sizeof(DataType)*s._size);
            memcpy(_array, s._array, sizeof(DataType)*s._size);
            _size = _capacity = s._size;
        }
        return *this;
    }
    ~SeqList()
    {
        if (_array)
        {
            free(_array);
            _size = _capacity = 0;
            _array = NULL;
        }
    }
    void Swap(SeqList& s)
    {
        swap(_array, s._array);
        swap(_capacity, s._capacity);
        swap(_size, s._size);
    }
    void PushBack(DataType x)
    {
        Insert(_size, x);
    }
    void PopBack()
    {
        Erase(_size - 1);
    }
    void PushFront(DataType x)
    {
        Insert(0, x);
    }
    void PopFront()
    {
        assert(_size > 0);
        Erase(0);
    }
    inline void Insert(size_t pos, DataType x)
    {
            assert(pos <= _size);
            CheckCapcacity();

        for (int end = _size - 1; end >=(int)pos; --end)
                {
                    _array[end + 1] = _array[end];
                }
                _array[pos] = x;
                ++_size;

        }
    inline void Erase(size_t pos)
        {
            assert(pos < _size);
            for (size_t i = pos + 1; i < _size;++i)
            {
                _array[i - 1] = _array[i];
            }
            --_size;
        }
    inline DataType& operator[](size_t pos)
        {
            assert(pos < _size);
            return _array[pos];
        }
        void CheckCapcacity()
        {
            if (_size == _capacity)
            {
                _capacity = _capacity * 2 + 3;
                _array = (DataType*)realloc(_array, _capacity*sizeof(DataType));
            }
        }
        void Print()
    {
            for (size_t i = 0; i < _size; ++i)
            {
                cout << _array[i] << " ";
            }
            cout << endl;
        }
private:
    DataType* _array;
    size_t _size;
    size_t _capacity;
};

猜你喜欢

转载自blog.csdn.net/important_/article/details/76889988