网站的新用户。在尝试实现通用SinglyLinkedList时,fetch返回null,而delete方法返回false,而fetch返回null。此外,当我决定以相反的顺序删除时,它的功能也很好。寻找一双新鲜的眼睛来看看我错过了什么。提前谢谢你。
public class SinglyLinkedList<T> {
private Node<T> h; // list header
public SinglyLinkedList() {
h = new <T> Node(); // dummy node
h.l = null;
h.next = null;
}
public boolean insert(T newNode) {
Node n = new Node();
GenericNode node = (GenericNode) newNode;
if (node == null) // out of memory
{
return false;
} else {
n.next = h.next;
h.next = n;
n.l = (T) node.deepCopy();
return true;
}
}
public GenericNode fetch(Object targetKey) {
Node p = h.next;
GenericNode node = (GenericNode) p.l; // this is where am I think there is a problem. Is this right?
while (p != null && !(node.compareTo(targetKey) == 0)) {
p = p.next;
}
if (p != null) {
return node.deepCopy();
} else {
return null;
}
}
public boolean delete(Object targetKey) {
Node q = h;
Node p = h.next;
GenericNode node = (GenericNode)p.l;// I think is the problem
while (p != null && !(node.compareTo(targetKey) == 0)) {
q = p;
p = p.next;
}
if (p != null) {
q.next = p.next;
return true;
} else {
return false;
}
}
public boolean update(Object targetKey, T newNode) {
if (delete(targetKey) == false) {
return false;
} else if (insert(newNode) == false) {
return false;
}
return true;
}
public void showAll() {
Node p = h.next;
while (p != null) //continue to traverse the list
{
System.out.println(p.l.toString());
p = p.next;
}
}
/**
*
* @param <T>
*/
public class Node <T> {
private T l;
private Node <T> next;
public <T> Node() {
}
}// end of inner class Node
}
//end SinglyLinkedList outer class发布于 2017-07-26 18:00:05
问题出在这里(在fetch方法中):
GenericNode node = (GenericNode) p.l; // this is where am I think there is a problem. Is this right?
while (p != null && !(node.compareTo(targetKey) == 0)) {
p = p.next;
}只在进入循环之前使用node,并且只在循环内更改p值,所以node在整个循环中都保持初始值不变。您应该使用:
GenericNode node = null; // define node before the loop in order to use it later
while (p != null) {
node = (GenericNode) p.l; // reset node value on each iteration
if (node.compareTo(targetKey) == 0) {
break;
}
p = p.next;
}由于您在delete中有相同的代码,因此将应用相同的修复程序...
https://stackoverflow.com/questions/45319257
复制相似问题