我正在尝试编写代码,以从列表中删除所有一项,但是当我尝试使用表示空指针异常的方法时遇到错误。
哪一行导致此错误,我该如何解决?删除项目后,它还应该返回true;如果没有出现,则返回false。
更新:错误是该行对象item2 = trav.item
public boolean removeAll(Object item){
Node trav = head;
while(trav != null){
Object item2 = trav.item;
// it could be `item2.equals`
if(item2.equals(item)){
trav.next = trav;
return true;
}
trav = trav.next;
}
return false;
}
最佳答案
除了我修复您的NPE。
如果您在修复删除代码时遇到问题,请查看此作为引用,它已经过测试。
我加入评论以解释正在发生的事情。
public class LList {
// very basic singly linked node
class Node {
public Node next;
public Object item;
public Node(Object o) {
item = o;
}
}
// the head and tail of this list
Node head = null;
Node tail = null;
public boolean removeAll(Object item) {
int count = 0;
if (head == null)
return false;
// while `head.item.equals(item)` remove the head
while (head != null && item.equals(head.item)) {
head = head.next;
count++;
}
// don't need to worry about updating `head` anymore
// because now `!head.item.equals(item)`, else `head == null`
if (head == null)
return count > 0;
// previous and current nodes
Node prev = head; // !head.item.equals(item)
Node curr = head.next;
while (curr != null) {
if (item.equals(curr.item)) {
// to remove `curr` make the previous node skip it
// and link to the next node instead
prev.next = curr.next;
count++;
} else {
// if curr was removed then prev stays put
// otherwise curr is the new prev
prev = curr;
}
// always move curr forward
curr = curr.next;
}
return count > 0;
}
关于java - 使用LLList的代码中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673702/