【问题标题】:linked list with dummy head java带有虚拟头java的链表
【发布时间】: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 false in while 循环看起来很可疑

标签: java data-structures singly-linked-list


【解决方案1】:

首先,在访问curr的数据之前添加null检查。还要删除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.
}

【讨论】:

  • 进入 while 循环时出现空指针异常。
  • 是的。这就是为什么我在if 条件中在while 循环之前添加了一个空检查
  • 在 while 循环中添加了 null 检查 cur.data
  • 尝试删除不存在的元素时给出空指针异常。
  • 有没有办法做一个 if 案例来检查最后一个节点何时为空以及何时结束所以它不会崩溃
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-04
  • 2013-03-15
  • 2019-03-01
  • 2012-04-06
  • 1970-01-01
相关资源
最近更新 更多