C++數據結構:順序表

代碼

#include <iostream>

using namespace std;

int aList[5];

template <class T>

class OrderList {
private:
    int maxSize;
    int curLen;
    int position;
public:
    OrderList() {
        curLen = position = 0;
    }
    //獲得順序表的長度
    int getLength() {
        return curLen;
    }
    //在表尾插入元素
    bool append(const T value) {
        if (curLen >= maxSize) {
            cout << "The list is overflow!" << endl;
            return false;
        }
        aList[curLen] = value;
        curLen++;
        return true;
    }
    //在指定位置插入元素
    bool insert(const int p, const T value) {
        int i;
        if (curLen >= maxSize) {
            cout << "The list is overflow!" << endl;
            return false;
        }
        else if (p <= 0 || p > maxSize) {
            cout << "Insertion point is illegal!" << endl;
            return false;
        }
        else {
            for (i = curLen; i > p; i--)
                aList[i] = aList[i - 1];
            aList[p] = value;
            curLen++;
            return true;
        }
    }
    //刪除某指定位置的元素
    bool drop(const int p) {
        int i;
        if (curLen >= maxSize) {
            cout << "The list is overflow!" << endl;
            return false;
        }
        else if (p <= 0 || p > maxSize) {
            cout << "Insertion point is illegal!" << endl;
            return false;
        }
        else {
            for (i = p; i < curLen; i++)
                aList[i] = aList[i + 1];
            aList[curLen] = '\0';
            curLen--;
            return true;
        }
    }
    //設定某指定位置的元素的值
    bool setValue(const int p, const T value) {
        int i;
        if (p <= 0 || p > maxSize) {
            cout << "Insertion point is illegal!" << endl;
            return false;
        }
        else {
            aList[p] = value;
            return true;
        }
    }
    //獲取某指定位置的元素的值
    bool getValue(const int p, T & value) {
        int i;
        if (p <= 0 || p > maxSize) {
            cout << "Insertion point is illegal!" << endl;
            return false;
        }
        else {
            value = aList[p];
            return true;
        }
    }
    //查找指定值所對應元素的位置
    bool getPos(int & p, const T value) {
        int i;
        for (i = 0; i < curLen; i++) {
            if (value == aList[i]) {
                p = i;
                return true;
            }
        }
        return false;
    }
};

測試

int main()
{
    int i;

    OrderList <int> test;
    test.append(1);
    test.append(2);
    test.append(4);
    cout << "Length: " << test.getLength() << endl;
    test.insert(2, 3);
    test.getValue(3, i);
    cout << "Position 3 " << " : " << i << endl;
    test.setValue(3, 5);
    test.getPos(i, 1);
    cout << "Position: " << i << endl;
    test.drop(4);
    return 0;
}

輸出

Length: 3
Position 3  : 4
Position: 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章