码迷,mamicode.com
首页 > 其他好文 > 详细

顺序表

时间:2016-09-13 01:32:20      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

#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];
    }
};

 好乱, 随时准备更新

顺序表

标签:

原文地址:http://www.cnblogs.com/QQ-1615160629/p/5867007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!