【发布时间】:2014-07-20 01:18:30
【问题描述】:
由于某种原因,我的插入函数不断返回 null 并打印出“未找到”。我觉得这与 head 为空且未分配为新节点这一事实有关。但我不能在 findKey 中执行此操作,因为它是一个私有类:
// findKey()
// returns a reference to the Node at key in the LinkedList; otherwise returns null
private Node findKey(String key){
Node N = head;
while(N != null){
N = N.next;
if(N.key.equals(key) && N.key != null){
return N;
}
}
return null;
}
public String lookup(String key){
if(findKey(key) == null){
System.out.println("not found");
return null;
}else{
Node N = findKey(key);
return N.value;
}
}
public void insert(String key, String value)
throws KeyCollisionException{
if(lookup(key)!= null ){
throw new KeyCollisionException(
"cannot create duplicate key");
}
if(head == null){
head = new Node(key,value);
return;
}else{
Node iter = head;
while(iter.next != null){
iter = iter.next;
}
Node N = new Node(key,value);
iter.next = N;
numItems++;
}
}
【问题讨论】:
-
你不能在
insert()中添加一个检查来查看head 是否为空吗?如果是那么只是自动添加当前键/值? -
我认为这就是我试图在行中做的:if(head == null){ head = new Node(key,value);返回;
-
你做了,但只是 在 调用
lookup()然后调用findKey()然后使用head(可能为 null)作为 N 的值。 -
哦,好吧。我在调用 lookup() 之前将支票移到了
-
这对你有用吗?如果是这样,我会将其发布为答案。
标签: java linked-list nodes