Splay樹的基本寫法

//node爲節點類型,其中ch[0]表示左結點指針,ch[1]表示右節點指針
//pre表示指向父親的指針

void Rotate(node *x,int c) //旋轉操作,c=0表示左旋,c=1表示右旋
{
    node *y= x->pre;
    Push_Down(y), Push_Down(x);
    //先將Y節點的標記鄉下傳遞(因爲Y在上面),再把X的標記向下傳遞
    y->ch[!c]=x->ch[c];
    if (x->ch[c] != NULL) x->ch[c]->pre = y;
    x->pre =y->pre;
    if (y->pre !=NULL)
        if (y->pre->ch[0] == y) y->pre->ch[0]=x;
        else y->pre->ch[1]=x;
    x->ch[c]=y;
    y->pre=x;
    Update(y);//維護Y節點
    if (y==root) root = x;//root表示整棵樹的根節點
}

void Splay(node *x,int *f)//Splay操作,表示把節點x轉到節點f的下面
{
    for (Push_Down(x);x->pre!=f ; )//一開始就將x的標記下傳
        if (x->pre->pre==f) //父節點的父親即爲f,執行單旋轉
            if (x->pre->ch[0]==x) Rotate(x,1);
            else Rotate(x,0);
        else {
            node *y=x->pre,*z=y->pre;
            if (z->ch[0]==y)
                if (y->ch[0]==x)
                    Rotate(y,1),Rotate(x,1);//一字型旋轉
                else 
                    Rotate(x,0),Rotate(x,1);//之字形旋轉
            else 
                if (y->ch[1]==x)
                    Rotate(y,0),Rotate(x,0);//一字型旋轉
                else 
                    Rotate(x,1),Rotate(x,0);//之字形旋轉
        }
    Update(x);//最後再維護x節點
}

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