我在这里有一个程序的小问题。我正在尝试创建一个程序,根据我们的hashFunction确定的hashCode,将单词添加到数组中的链接列表。如果它们的hashCode具有相同的值,则会将它们添加到链接列表中。我有一个小计数方法,计算一个单词在列表中的次数。它的工作原理是计算hashFunction的值。然后它转到数组中的该值,并遍历LinkedList直到它达到Null值。它有一个count变量,每次在列表中找到单词时都会递增。这是我的代码:
public class test{
public static class Node<T>{
public T data;
public Node<T> next;
public Node(){
}
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}
}
static Node[] array = new Node[512];
public static void add(String word){
int position = hashFunction(word);
if(array[position] == null){
array[position] = new Node(word, null);
}else{
Node newHead = new Node(word, array[position]);
array[position] = newHead;
}
}
public static void remove(String word){
int remove = hashFunction(word);
Node head = array[remove];
if(head.data == word){
head = head.next;
System.out.println("Found");
}else if(head.data != word){
for(; array[remove] != null; array[remove] = array[remove].next){
if(array[remove].data == word){
array[remove] = array[remove].next;
}
}
System.out.println("Yusuf");
}
}
public static int count(String word){
int number = 0;
int position = hashFunction(word);
for(; array[position] != null; array[position] = array[position].next){
if(array[position].data == word){
number++;
}
}
System.out.println(number);
return number;
}
public static int hashFunction(String a){
int sum = 1;
for(int i = 0; i<a.length(); i++){
char b = a.charAt(i);
int value = (int) b;
sum *= value;
}
return sum % array.length;
}
public static void addthings(String word, int n){
for(int i = 0; i<n; i++){
add(word);
}
}
public static void main(String[] args) {
addthings("abc", 500000);
count("abc");
count("abc");
count("abc");
count("abc");
}
}
我的问题是我第一次在其中添加值并检查它发生了多少次它工作正常,但在此之后再调用Count方法由于某种原因返回0。
我还有另一个问题,即我的删除方法是不是从链接列表中删除项目我也想要它。代码遍历List,当它找到要删除的项时,它会从那里删除指针并将其指向下一个值。但这并不起作用。
有人可以告诉我如何解决这两个问题吗?
感谢。
答案 0 :(得分:0)
在您的函数中,如果您编写Node head
内容,则表示您正在为节点创建一些本地实例。如果设置head = head.next
,则只会更改本地实例变量的状态而不是数组的状态。
您正在检查第一个节点是否包含您正在查找的数据并尝试将其删除,然后您必须将其从源数组(您的引用所在的数组)中删除。所以您可以这样写:< / p>
if(head.data == word)
array[remove] = head.next;
这是一个例子。关键是你不是在数组中查找东西,而是在你的局部变量中。
public static void remove(String word){
int remove = hashFunction(word);
Node head = array[remove];
if(head.data == word){
head = head.next;
System.out.println("Found");
}else if(head.data != word){
for(; array[remove] != null; array[remove] = array[remove].next){
if(array[remove].data == word){
array[remove] = array[remove].next;
}
}
System.out.println("Yusuf");
}
}
第二个错误是在第二个子句中,您只需设置array[remove] = array[remove].next;
它会将您的链表分成两个不同的链表。假设您在链表A,B,C,D
中有4个元素并删除了B
,并且有像A->B->C->D
这样的指针,那么您不会添加A -> C
的指针。在这里你可以打破链表。
您可以使用易于使用的while循环。