2013-04-10 98 views
2

我正在處理作業,並遇到了我的代碼問題。在作業中,我們需要一系列數字,將它們散列,然後將它們放入數組中,其中每個位置都是鏈接列表。我已經爲鏈表(稱爲MyList)編寫了類,並且編寫了將整數放入數組中的代碼,如果該數組中沒有任何內容。我遇到的問題是當我嘗試打印時,數組中的每個位置都繼續爲「空」。我在這裏犯了一個愚蠢的錯誤還是我的方法有缺陷?謝謝。陣列中每個位置的鏈接列表

public class MyHashTab { 

public MyHashTab(int initialCapacity, MyList[] anArray) { 

} 


public static void insert(int searchKey, MyList[] anArray) { 

    int hash = searchKey % anArray.length; 

    MyList current = new MyList(); 

    current.iData = searchKey; 

    if (anArray[hash] == null) { 

     current = anArray[hash]; 

    }else{ 

     insertMyList(current, anArray); 

    } 

} 

public static void insertMyList(MyList current, MyList[] anArray) { 

    System.out.println("We are here."); 
} 

public static void printHash(MyList[] anArray) { 

    System.out.println("The generated hash table with separate chaining is: "); 

    for (int i = 0; i < anArray.length; i++) { 

     System.out.println("The items for index[" + i + "]: " + anArray[i]); 

    } 
} 

} 

public class MyList { 

int iData; // This integer is used as a key value, and as a way to see the actual node instead of it's memory address. 
MyList current; 
MyList previous; // This is a pointer to a nodes left child. Pointing seems rude, but they sometimes point to null which, as well know, is less rude. 
MyList next; // This is a pointer to a nodes right child. 

} 

回答

3

您的插入邏輯反轉。取而代之的

current = anArray[hash]; 

應該

anArray[hash] = current; 

我相信你也應該調用insertMyList(current, anArray)不管陣列位置是否原是空,所以邏輯應該

if(anArray[hash] == null) { 
    anArray[hash] = new MyList(); 
} 
insertMyList(anArray[hash], anArray); 
+0

這並它!謝謝Zim-Zam。我相當肯定,我花在分配問題上的時間比任何其他錯誤都多。再次感謝。 – joerdie 2013-04-10 15:20:19