[英]linked list with dummy head java
I am trying to remove data elements from a singly linked list with a dummy head. 我正在尝试从带有虚拟头的单链接列表中删除数据元素。 The list can include null data elements, and thats the part where i'm stuck.
该列表可以包含空数据元素,这就是我所卡住的部分。 The data is passed in is of Object type.
传入的数据为对象类型。 This is what I got so far
这就是我到目前为止
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.
}
this is the linked list class 这是链表类
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;
}
First of all, add a null
check before accessing data of curr
. 首先,在访问
curr
数据之前添加一个null
检查。 Also remove the return false
in while
loop as it ends your loop prematurely without checking all the elements in list. 还要在
while
循环中删除return false
,因为它过早地结束了循环,而无需检查列表中的所有元素。
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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.