【发布时间】:2021-03-30 06:34:58
【问题描述】:
我是编程新手。我目前正在学习 Java 编程语言。我的问题是,我正在尝试删除包含 HashTable 中的值的特定节点,但我无法弄清楚我哪里出错了。有人可以向我解释如何删除这个特定节点吗?先感谢您。对不起我的英语不好。
我想要瞄准的输出:"Albert" 和 "Timmy" 应该被删除。
这是我的代码:
类:HashEntry
public class HashEntry {
private int key;
private String value;
private HashEntry next;
public HashEntry() {
this.next = null;
}
public HashEntry(int key, String value) {
this.key = key;
this.value = value;
this.next = null;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
public void setNext(HashEntry next) {
this.next = next;
}
public HashEntry getNext() {
return this.next;
}
}
类:HashTableArray
public class HashTableArray {
HashEntry[] arrayHash;
int size;
public HashTableArray(int size) {
this.size = size;
arrayHash = new HashEntry[size];
}
public int getHash(int key) {
return key % size;
}
public void insert(int key, String value){
int hashInd = getHash(key);
HashEntry newVal = new HashEntry(key, value);
if (arrayHash[hashInd] == null) {
arrayHash[hashInd] = newVal;
}
else {
HashEntry arrayValue = arrayHash[hashInd];
while (arrayValue.getNext() != null) {
arrayValue = arrayValue.getNext();
}
arrayValue.setNext(newVal);
}
}
public void displayTable() {
System.out.println("Hash Table:");
for (int i=0; i<arrayHash.length; i++) {
if(arrayHash[i] != null) {
HashEntry temp = arrayHash[i];
while(temp.getNext() != null) {
System.out.println(temp.getKey() + ", " + temp.getValue());
temp = temp.getNext();
}
System.out.println(temp.getKey() + ", " + temp.getValue());
}
}
}
public void delete (int key, String value) {
int hashInd = getHash(key);
HashEntry head = arrayHash[hashInd];
if (arrayHash[hashInd] != null) {
HashEntry temp = head, prev = null;
if (temp.getNext() == null && head.getValue().equalsIgnoreCase(value)) {
head = null;
}
else if (temp.getNext() != null && temp.getValue().equalsIgnoreCase(value)) {
head = temp.getNext();
}
else {
while(!temp.getValue().equalsIgnoreCase(value)) {
prev = temp;
temp = temp.getNext();
}
if (temp == null) {
prev.setNext(null);
}
else {
prev.setNext(temp.getNext());
}
}
}
}
}
类:HashTableProgram
public class HashTableProgram {
public static void main(String[] args) {
HashTableArray h = new HashTableArray (10);
h.insert(12, "Albert");
h.insert(26, "Johnson");
h.insert(5, "Timmy");
h.insert(12, "George");
h.displayTable();
h.delete(12, "Albert");
h.delete(5, "Timmy");
System.out.println("\nAfter deleted...");
h.displayTable();
}
}
【问题讨论】: