[英]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.