[英]Implementation of a Generic Singly Linked List
New to the site. 该网站的新手。 Trying to implement a generic SinglyLinkedList, fetch returns null even though there are nodes in and delete method return false, when true is expected.
尝试实现通用SinglyLinkedList时,即使其中包含节点,fetch也会返回null,而delete方法则返回false(如果期望为true)。 In addition, it functions just fine when I decide to delete in reverse order.
另外,当我决定以相反的顺序删除时,它的功能也很好。 Looking for a set of fresh eyes to see what I am missing.
寻找一组新鲜的眼睛,看看我缺少什么。 Thanks-in-advance.
提前致谢。
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
The problem lies here (in fetch
method): 问题就在这里(在
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;
}
You assing node
only only before entering the loop, and only change p
value inside the loop, so node
keeps its initial value throughout the whole loop. 仅在进入循环之前才对
node
赋值,并且仅在循环内更改p
值,因此node
在整个循环中都保持其初始值。 You should use: 您应该使用:
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;
}
As you have same code in delete
, the same fix will apply... 由于您在
delete
具有相同的代码,因此将应用相同的修复程序...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.