已解决:代码反映解决方案
我一直在处理自定义链接列表,只需使用对列表的一个引用删除具有给定键的节点。
我已经设法用两个引用(节点先前,节点当前)来做到这一点,但是如果仅使用一个引用方法有点困惑。
我的代码适用于除了删除头节点以及尝试删除'88'或不存在'100'的节点时不在列表中的节点(我得到nullpointer异常)的情况。
Here is my test data from the list:
0) 88
1) 2
2) 1
3) 8
4) 11
// Iterative method to delete a node with a given integer key
// Only uses ONE reference variable to traverse the list.
private void delete (int key, Node x) {
// Check if list is empty
if (isEmpty()) {
System.out.println("Cannot delete; the list is empty.");
}
// Check if we're deleting the root node
if (key == head.getKey()) {
// Now the first in the list is where head was pointing
removeFromHead();
}
// General case: while the next node exists, check its key
for (x = head; x.getNext() != null; x = x.getNext()) {
// If the next key is what we are looking for, we need to remove it
if (key == x.getNext().getKey()) {
// x skips over the node to be deleted.
x.putNext(x.getNext().getNext());
}
} // End for
}
答案 0 :(得分:1)
试试这个:
public Value delete (int key) {
//check if list is empty
if (head == null)
//the key does not exist. return null to let the method caller know
return null;
//check if we're deleting the root node
if (key == head.getKey()) {
//set the value of what we're deleting
Value val = head.getNode().getValue();
//now the first in the list is where head was pointing
head = head.getNext();
//there is now one less item in your list. update the size
total--;
//return what we're deleting
return val;
}
// general case: while the next node exists, check its key
for (Node x = head; x.getNext() != null; x = x.getNext()) {
//check if the next node's key matches
if (key == x.getNext().getKey()) {
//set value of what we're deleting
Value val = x.getNext().getNode().getValue();
//x now points to where the node we are deleting points
x.setNext(x.getNext().getNext());
//there is now one less item in the list. update the size
total--;
//return what we're deleting
return val;
}
}
//if we didn't find the key above, it doesn't exist. return null to let the
// method caller know.
return null;
}
这是LinkedList
。一般的想法是存在的,但你必须根据你如何设置一切来定制它。<Value>
答案 1 :(得分:0)
嗯,你的列表的头部和尾部有问题,因为你没有正确检查它们。
您应该在进入while循环之前比较头部的键。循环检查的第一个值是第二个节点(temp.getNext().getKey()
),因此您永远不会实际测试头部。
此外,在循环结束后,您检查密钥是否在最后一个节点中,您还要调用getNext()
。如果确实是最后一个节点,则下一个节点为空,并且没有getKey()
方法。