[英]Implementation of a Generic Singly Linked List
該網站的新手。 嘗試實現通用SinglyLinkedList時,即使其中包含節點,fetch也會返回null,而delete方法則返回false(如果期望為true)。 另外,當我決定以相反的順序刪除時,它的功能也很好。 尋找一組新鮮的眼睛,看看我缺少什么。 提前致謝。
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
問題就在這里(在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
具有相同的代碼,因此將應用相同的修復程序...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.