循環鏈表臨時實現以及一些問題

queue不能遍歷,就想着自己寫個能遍歷的隊列,尋思着就寫了個循環鏈表,完全跑題了,但是也發現了一些問題

 

一個結構體:

struct A
{
    int x;
    A(int x):x(x){}
};

 循環鏈表:

struct danmuLb{
    A *x;
    
    static danmuLb *head;
    static danmuLb *tail;

    danmuLb *next;
    danmuLb *previous;

    danmuLb(A &X):
        x(&X)
    {
        previous = (danmuLb::tail == nullptr)?this: danmuLb::tail;
        next = previous->next;

        previous->next = this;
        next->previous = this;

        if(danmuLb::tail == nullptr)    danmuLb::head = this;
        danmuLb::tail = this;
    }

    ~danmuLb(){
        danmuLb::tail = (next == this)?nullptr: previous;
        if(danmuLb::tail == nullptr)    danmuLb::head = nullptr;

        previous->next = next;
        next->previous = previous;

        delete x;
    }
    void print()    {cout<<"num of this is "<<x->x<<endl;}

    // queue這種鏈表沒做迭代器的原因找到了!
    // 沒法讓指針重載自增++
    
    static void destroy()   {
        danmuLb *now = danmuLb::head;
        danmuLb *tmp;
        while(now->next != now){
            tmp = now->next;
            delete now;
            now = tmp;
        }
        delete now;
    }
};
danmuLb *danmuLb::head = nullptr;
danmuLb *danmuLb::tail = nullptr;

main函數:

int main(){
    // 記下來研究一下
    // new danmuLb(A(2));
    new danmuLb(*(new A(2)));
    new danmuLb(*(new A(3)));

    cout<<typeid(A(8)).name()<<endl;
    cout<<typeid(*(new A(4))).name()<<endl;
    // new danmuLb(new A(3));

    //...
    danmuLb *tmp = tmp->head;

    tmp->print();
    tmp = tmp->next;
    tmp->print();
    tmp = tmp->next;
    tmp->print();
    tmp = tmp->next;
    tmp->print();
    tmp = tmp->next;
    tmp->print();

    tmp->destroy();

    cout<<tmp->head<<' '<<tmp->tail;

    return 0;
}

 

問題:

  1. 自定義類型的指針的運算符能不能遍歷?
  2. 關於不能new danmuLb(A(2)), 爲什麼不返回臨時數據A(2)的引用,對聲明的具體過程還不夠熟悉

 

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