2013-04-10 52 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