線性表的順序實現(c++)

 

前言:

在學習了一些算法的基礎知識後,我開始了對數據結構的新一輪轟炸。數據結構和算法作爲計算機科學的基礎學科,必須要好好學,對不對?剛剛入了門,先來看看數據結構的線性結構,其下有線性表、棧、隊列等等我們都聽着耳熟能詳的的結構(只是耳熟,其實並不知道詳細是啥)。今天就先來看看線性表的順序實現:

線性表的順序實現:

模板基類:

template<class elemType>
class list
{
public:
    virtual void clear() = 0;            //clear all elements in list
    virtual int length()const = 0;       //get the length of list
    virtual void insert(int i, const elemType &x) = 0;  //insert an element in list
    virtual void remove(int i) = 0;       //remove an list in list
    virtual int search(const elemType &x)const = 0;     //search the element
    virtual elemType visit(int i)const = 0;             //visit the element
    virtual void traverse()const = 0;    //visit every element in list
    virtual ~list(){};
};

子類線性表的順序實現:

template <class elemType>
class seqList:public list<elemType>
{
private:
    elemType *data;                     //seqlist--data
    int currentLength;                  //current length of seqlist
    int maxSize;                        //max size of seqlist
    void doubleSpace(){
        int i;
        elemType *tmp = data;
        maxSize = maxSize * 2;
        data = new elemType[maxSize];
        for(i = 0; i < currentLength; i++){
            data[i] = tmp[i];
        }
        delete []tmp;
    }
    
public:
    seqList(int initSize = 10){
        maxSize = initSize;
        data = new elemType[maxSize];
        currentLength = 0;
    }
    
    ~seqList(){
        delete []data;
    }
    
    void clear(){
        currentLength = 0;
    }
    
    int length()const{
        return currentLength;
    }

    void insert(int i, const elemType &x){
        int j;
        if(currentLength == maxSize){
            doubleSpace();
        }
        else{
            for(j = currentLength; j > i; j--){
                data[j] = data[j - 1];
            }
            data[i] = x;
        }
        currentLength = currentLength + 1;
    }
    
    void remove(int i){
        int j;
        for(j = i; j < currentLength - 1; j++){
            data[j] = data[j + 1];
        }
        currentLength = currentLength - 1;
    }
    
    int search(const elemType &x)const{
        int i;
        for(i = 0; i < currentLength && data[i] != x; i++);
        if(i == currentLength){
            return -1;
        }
        else{
            return i;
        }
    }
    
    elemType visit(int i) const{
        return data[i];
    }
    
    void traverse() const{
        int i;
        cout << endl;
        for(i = 0; i < currentLength; i++){
            cout << data[i] << " ";
        }
        cout << endl;
    }
};

總結:

線性表的順序實現中由於邏輯次序與物理次序的一致性,使得定位訪問的性能很好,但在插入和刪除時需要移動大量的數據,性能不太理想。

 

 

以上內容純屬個人學習總結,不代表任何團體或單位。若有理解不到之處請見諒!

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