我正在尝试使用虚拟头从单个链接列表中删除数据元素。该列表可以包含空数据元素,这就是我被卡住的部分。传入的数据是Object类型。这是我到目前为止所得到的
public boolean remove(Object o) {
ListNode prev= this.head, cur = this.head.next;
if(size == 0)
return false;
while(!cur.data.equals(o)){
prev = cur;
cur = cur.next;
return false;
}
if(cur == null)//not existing
return false;
prev.next = cur.next;
this.size--;
return true; //change this as you need.
}
这是链表类
public class MyLinkedList {
private ListNode head;
private int size;
//inner class for ListNode
private class ListNode {
private Object data;
private ListNode next;
private ListNode(Object d) {
this.data = d;
this.next = null;
}
}
public MyLinkedList() {
this.head = new ListNode(null); //with a dummy head node
this.size = 0;
}
答案 0 :(得分:0)
首先,在访问null
的数据之前添加curr
检查。同时删除return false
循环中的while
,因为它会过早地结束循环,而不会检查列表中的所有元素。
public boolean remove(Object o) {
ListNode prev= this.head, cur = this.head.next;
if(size == 0 || cur ==null) // add null check here
return false;
while(cur.data!=null && !cur.data.equals(o)){
prev = cur;
cur = cur.next;
//return false;
}
if(cur == null)//not existing
return false;
prev.next = cur.next;
this.size--;
return true; //change this as you need.
}