[英]Implementing isEmpty() for Linked Dictionary from scratch in Java
目前,我正在開展一個項目,在該項目中我從頭開始實現鏈接字典接口。 一路順風,直到我意識到我的代碼聲稱一旦看到單個空值,整個字典就是空的。
public class LinkedDictionary<K, V> implements Dictionary<K, V> {
/** List node. */
private class Node {
K key;
V value;
Node next;
Node(K key, V value, Node next) {
this.key = key;
this.value = value;
this.next = next;
}
}
/** The first node in this dictionary, or null if this dictionary is empty. */
private Node front;
@Override
public void put(K key, V value) {
if(value == null) { // if a null value is given, the dictionary is empty
isEmpty();
return;
}
for (Node n = front; n != null; n = n.next) {
if (n.key.equals(key)) {
return;
}
}
front = new Node(key, value, front); // front node now contains new key and value
}
@Override
public V get(K key) {
if (key == null) // if a null key is given, null is returned
return null;
for (Node n = front; n != null; n = n.next) {
if (n.key.equals(key)) {
return n.value; // if they key is within the contents of the dictionary, return the corresponding value
}
}
return null; //if the key does not appear in the dictionary, null is returned.
}
@Override
public boolean isEmpty() {
return front == null;
}
}
我很清楚我的問題。 在我的“put”方法中,如果用戶嘗試輸入空值,整個字典都會被標記為“空”。 我在想象這樣的場景:
Dictionary<Integer, String> d = new LinkedDictionary<>();
d.put(1, "one");
d.put(2, "two");
d.put(1, null);
一旦我的實現到達鍵 1 設置為空的第三行,它就會將整個字典設置為空,盡管鍵 2 處仍然存在有效條目。我一直在絞盡腦汁關於如何更改我的代碼以允許這種情況,但我無法弄清楚。 我試過改變我的 isEmpty 方法,我什至嘗試添加一個額外的方法,但我似乎無法弄清楚在這里做什么!
任何指向正確方向的指針或推動將不勝感激!
public final class LinkedDictionary<K, V> {
private Node<K, V> head;
private Node<K, V> tail;
private int size;
public int getSize() {
return size;
}
public void put(K key, V value) {
Objects.requireNonNull(key, "Node.key");
Node<K, V> node = new Node<>(key, value);
remove(key);
if (isEmpty())
head = node;
else
tail.next = node;
size++;
tail = node;
}
public V remove(K key) {
Objects.requireNonNull(key, "Node.key");
if (isEmpty())
return null;
if (head.key.equals(key)) {
V value = head.value;
head = head.next;
tail = head == null ? null : tail;
size--;
return value;
}
Node<K, V> prv = head;
Node<K, V> it = head;
while (it != null) {
if (it.key.equals(key)) {
V value = it.value;
prv.next = it.next;
it.next = null;
size--;
return value;
}
prv = it;
it = it.next;
}
return null;
}
public V get(K key) {
Objects.requireNonNull(key, "Node.key");
Node<K, V> node = head;
while (node != null) {
if (node.key.equals(key))
return node.value;
node = node.next;
}
return null;
}
public boolean isEmpty() {
return head == null;
}
private static class Node<K, V> {
private final K key;
private final V value;
private Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.