首页 > 代码库 > 顺序表

顺序表

#include <iostream>using namespace std;const int defaultSize = 100;template <typename T>class SeqList{protected:    T *data;    int maxSize;    int last;    void reSize(int newSize)    //ok    {        maxSize = newSize;        T *temp = new T[maxSize];                for (int i = 0; i <= last; i++)            temp[i] = data[i];        delete[] data;        data = temp;    }public:    SeqList(int sz = defaultSize) : maxSize(sz), last(-1) //ok    {        data = new T[maxSize];    }    SeqList(SeqList<T> &L)    //ok    {        maxSize = L.maxSize;        last = L.last;        data = new T[maxSize];        for (int i = 0; i <= last; i++)            data[i] = L.data[i];    }    ~SeqList() { delete[] data; }    //ok    int Size() const { return maxSize; } //ok    int Length() const { return last + 1; }    //ok    int Search(T &x) const    //ok    {        for (int i = 0; i <= last; i++)            if (data[i] == x) return i + 1;        return -1;    }    int Locate(int i) const // ok    {        return data[i - 1];    }    bool getDate(int i, T &x) const    //ok    {        if (i > 0 && i <= last + 1)        {            x = data[i - 1];            return true;        }        else return false;    }    void setData(int i, T &x)    //ok    {        if (i > 0 && i <= last + 1) data[i - 1] = x;    }    bool Insert(int i, T &x) //ok    {        if(i > last + 2) return false;        if (last + 1 == maxSize) reSize(maxSize * 2);        int p = last;        while (p >= (i - 1))            data[p + 1] = data[p--];        data[++p] = x;        last++;        return true;    }    bool Remove(int i, T &x)    //ok    {        if(last != -1)        {            last--, x = data[i - 1];            for (int p = i - 1; p <= last; p++)                    data[p] = data[p + 1];        }    }    bool IsEmpty() { return (last == -1) ? true : false; }    //ok    bool IsFull() { return (last + 1 == maxSize) ? true : false; }    //ok    void input()    //ok    {        cin >> last;        last--;        for (int i = 0; i <= last; i++)            cin >> data[i];    }    void output()    //ok    {        cout << "{";        for (int i = 0; i < last; i++)            cout << data[i] << ", ";        cout << data[last] << "}" << endl;    }    SeqList<T> operator = (SeqList<T> &L)    //ok    {        if (L.last >= maxSize) reSize(L.maxSize);        last = L.last;        for (int i = 0; i <= last; i++)            data[i] = L.data[i];    }};

 好乱, 随时准备更新

顺序表