与虚拟头java的链表 [英] linked list with dummy head java
本文介绍了与虚拟头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.
}
这是链表类
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;
}
推荐答案
首先,在访问 curr
的数据之前,先添加 null
检查.另外,请在 while
循环中删除 return false
,因为它会提前结束循环,而无需检查列表中的所有元素.
First of all, add a null
check before accessing data of curr
. Also remove the return false
in while
loop as it ends your loop prematurely without checking all the elements in list.
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.
}
这篇关于与虚拟头java的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文