从列表中查找并删除所有出现的给定信息。 (仅遍历列表一次。)
我可以获取要删除的列表中的第一个号码 如果我选择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;
}
}
}
}
}
答案 0 :(得分:1)
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;
}
}
答案 1 :(得分:0)
在删除集合内的元素(而不是第一个)时,看起来像指针有点错误。尝试使用赋值:
trailCurrent.link = current.link;
而不只是:
trailCurrent = current.link;
答案 2 :(得分:0)
您需要将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
trail 应保持不变(指向A); trail.link 应该从A更改为C,即 curr.link 以删除节点B.此外 curr 也应该开始指向C用于while
循环的下一次迭代。