亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用三個參數將節點插入到 Treap 上

如何使用三個參數將節點插入到 Treap 上

呼如林 2024-01-25 21:30:38
我在將 Treapnode 插入 Treap 時遇到問題。它接受 3 個參數。添加(E 鍵,P 優先級,treapnode x)。我嘗試了很多方法,但總是出現空指針異常。我嘗試檢查左右樹中的空情況。private TreapNode add (E key, P priority, TreapNode x)        throws ElementFoundException {    // For You To Complete    int compare = key.compareTo(x.element());    if (x == null){        return new TreapNode(key, priority);    }    //root is larger than the key    else if (compare == 0) {        throw new ElementFoundException("Element was found, and tree was not changed.");    } else if (compare < 0) {        if (x.left() == null) {         //TreapNode y = new TreapNode(key, priority);            TreapNode y = x.left;            x.left = y.right;            y.right = x;            return y;        } else {            x.left = add(key, priority, x.left());        }    }    //root is smaller than the key    else if (compare > 0) {        if (x.right() == null) {            //TreapNode y = new TreapNode(key, priority);            TreapNode z = x.right;            x.right = z.left;            z.left = x;            return z;        }    }    return x;}
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

這是你做錯了x.right()。情況也是如此x.left()


if (x.right() == null) {

? ? ? ? //TreapNode y = new TreapNode(key, priority);

? ? ? ? TreapNode z = x.right; // z = null

? ? ? ? x.right = z.left;? // z.left will throw NPE

應該


if (x.right() == null) {

? ?x.right() = new TreapNode(key, priority);

? ?return x; // return parent node?

}

另外,我認為這也是一個錯誤的比較,int不能null但是Integer類可以


int compare = key.compareTo(x.element());? //comoareTo return an int?

if (x == null){? // does not make sense to compare and int type to Object type

? ....

}


查看完整回答
反對 回復 2024-01-25
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號