从列表中查找并删除所有出现的给定信息。(只遍历列表一次。)
我可以得到列表中第一个要删除的号码如果我选择1。
名单是"1 3 4 6 7"1将被删除,计数将像预期的那样减少到4。
public void deleteAll(T deleteItem) {
LinkedListNode<T> current ; // variable to traverse the list
LinkedListNode<T> trailCurrent ; // variable just before current
// boolean found;
if (first == null) // Case 1; the list is empty
System.err.println("Cannot delete from an empty " + "list.");
else {
if (first.info.equals(deleteItem)) // Case 2
{
first = first.link;
if (first == null) // the list had only one node
last = null;
count--;
}
else{
trailCurrent = first;
current = first.link;
while(current != null){
if(current.info.equals(deleteItem)){
trailCurrent = current.link;
count--;
}
else
{
trailCurrent = current;
current = current.link;
}
}
}
}
}
public static void deleteKey(LinkedList list, int key) {
if(list == null) {
return;
}
Node temp = list.head;
Node prev = null;
// If head node itself holds the key or multiple occurrences of key
while(temp != null && temp.data == key) {
list.head = temp.next;
temp = list.head;
}
while(temp !=null) {
if(temp.data == key) {
prev.next = temp.next;
} else {
prev = temp;
}
temp = temp.next;
}
}
在删除集合内的元素(不是第一个)时,似乎分配指针有点错误。尝试使用分配:
trailCurrent.link = current.link;
而不仅仅是:
trailCurrent = current.link;
您需要将while
循环的if
子句修复为
if (current.info.equals(deleteItem)) {
trailCurrent.link = current.link; // deletes current from list
current = current.link; // updates current pointer
count--;
}
对于要删除节点B 的一组三个节点
A --> B --> C
| |
trail curr
轨迹应保持不变(指向A)trail.link应从A更改为C,即curr.link删除节点B。除此之外,curr.link还应在while
循环的下一次迭代中开始指向C。