【发布时间】:2018-04-12 09:33:47
【问题描述】:
我正在尝试从带有虚拟头的单链表中删除数据元素。该列表可以包含空数据元素,这就是我卡住的部分。传入的数据是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;
}
【问题讨论】:
-
return falseinwhile循环看起来很可疑
标签: java data-structures singly-linked-list