0
该网站的新功能。试图实现一个通用的SinglyLinkedList,即使存在节点并且delete方法返回false,当预期为true时,获取返回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
这可能属于代码审查页:https://codereview.stackexchange.com/ – Lino
我们需要你的'SinglyLinkedList'的实现来告诉你它失败的地方 – XtremeBaumer
请原谅我,只是添加它。我以为我已经包括它。 – Patel