簡體   English   中英

TreeMap實現的put方法

[英]Put method of a TreeMap implementation

我正在開發TreeMap(稱為MyTreeMap)的實現,但是put方法遇到了很多麻煩。 我希望有人可以查看我的代碼,並向我指出發生錯誤的正確方向。

public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V>  {

K key;
V value;
int height;
MyTreeMap<K,V> left,right;
int size;

public V put(K key, V value) {

    int compareValue = this.key.compareTo(key);

    if(!this.containsKey(key)) {
        if(this.key == null) {
            this.key = key;
            this.value = value;
        }

        if(this.isLeaf() || this.isEmpty()) {
            if(this.key.compareTo(key) > 0)
                this.left = new MyTreeMap<K,V>(key,value,null,null);
            else
                this.right = new MyTreeMap<K,V>(key,value,null,null);

            if(left.height > right.height + 1 || right.height > left.height + 1)
                restructure(this);
            this.size++;
            setHeight();
            return null;
        }
        else {
            if(compareValue > 0)
                return this.left.put(key, value);
            else
                return this.right.put(key, value);
        }
    }

    else {
        if(compareValue == 0) {
            V temp = this.value;
            this.value = value;
            return temp;
        }

        else if(compareValue < 0)
            return this.right.put(key, value);
        else 
            return this.left.put(key, value);
        }
}

我認為您的邏輯有點由內而外,結果比所需的要復雜得多:頂層if應該查看compareValue ,而不是執行containsKey檢查。

邏輯應為:

  • 如果compareValue==0則意味着您找到了正確的鍵,因此只需更新值並返回
  • 否則,請根據需要檢查向左或向右分支(取決於compareValue的符號):
    • 如果分支為null,則將其轉換為包含您的鍵和值的新TreeMap分支(現已完成)
    • 否則(分支不為null),請對該分支進行遞歸調用。 如果願意,您可以在此調用之后進行邏輯重新平衡。

PS:我建議在TreeMap中不允許使用空鍵,這會使您的生活更簡單,並且避免對鍵進行空值檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM