【问题标题】:addFirst() in a custom LinkedList自定义 LinkedList 中的 addFirst()
【发布时间】:2013-10-01 21:33:18
【问题描述】:

我正在使用 customLinkedLists 的 LinkedList,但在实现 AddFirst 方法时遇到了一些问题。

方法如下,

public void addFirst(GenericType data)
{
  Node<GenericType> toAdd = new Node<GenericType>(data);

  if(sizeCounter != 0)
  {
    toAdd.next = head;
    head = toAdd;
    sizeCounter++; 
  } else {
    head = toAdd;
    tail = toAdd;
    toAdd.next = null;
    sizeCounter++;
  }
}

问题是每次我调用它时都会正确增加大小,但是当我尝试打印出值时,它会引发空指针异常。 我知道我设置头/尾指针的方式存在问题,但我无法弄清楚它到底是什么。

编辑: 基本上我有一个 OuterList 和一个自定义的 LinkedList 类。

在外部列表类中,我有一个对象:

LinkedList<CustomList<GenericType>> oList = new LinkedList<CustomList<GenericType>>;
//method add in OuterList class that calls addFirst in customLinkedClass
public void add(GenericType x){
  oList.get(0).addFirst(x);
}

//Prints the List
public void print(){
  for(int i=0; i<oList.size(); i++){
    for(int j=0; j<oList.get(i).size(); j++){
      // first .get() is for the oList to get the first customLinkedList.
      // second .get() returns the value of the Node in the customLinkedList
      System.out.println(oList.get(i).get(j));
    }
}

当我在添加项目后尝试转储时,它会抛出一个空指针。当我创建customLinkedList 时,设置head.next = tail。这可能是问题的原因吗?我不明白为什么它会给我错误

编辑2:

堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
      at squarelist.CustomList.get(CustomList.java:187)
      at squarelist.OuterList.dump(OuterList.java:94)
      at squarelist.OuterList.main(OuterList.java:106)

它出现在的行:

public GenericType get(int index){ return getNodeAt(index).value; }

getNodeAt() 函数:

private Node<GenericType> getNodeAt( int index ){
  Node<GenericType> p = null;
  p = head.next;
  for( int i = 0; i < index; i++ ){
    p = p.next; 
  }
  return p;
}

【问题讨论】:

  • 变量add是什么?
  • 你能在你得到错误的地方添加代码吗?
  • 贴出堆栈跟踪和异常发生的行号
  • 查看else 部分的if 语句:此时add 变量包含什么?这就是导致您的NPE 的原因。
  • @GermannArlington 我纠正了错误,错误仍然存​​在。

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


【解决方案1】:

改变这个:

head = add;
tail = add;

到这里:

head = toAdd;
tail = toAdd;

在 else 块中

编辑

发布堆栈跟踪后,问题是您从 getNodeAt 方法返回 null。

假设列表中只有一个元素;那么p = head.next; 将为空,您将返回该值。

尝试设置p=head

【讨论】:

  • 是的,那是我的一个错误,我忘了改变那些。但错误仍然存​​在。不断抛出空指针
  • [忘记标记] @richardtz
  • 非常感谢,这是造成问题的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多