2016-11-14 66 views
-1

我在Java中使用单向链表实现一个双端队列。我的addFirst()功能工作正常,但addLast()不起作用。我正在使用Java中的单向链表实现一个双端队列。我的addLast()不起作用

每当我打电话addLast(),我得到了以下错误消息:

显示java.lang.NullPointerException

This is my function implementations

+0

“NullPointerException”中包含的完整堆栈跟踪是什么?你的错误控制台会告诉你哪一行引发了异常,以及那个被调用到那个点上的所有东西?另外,请在提问时将代码作为文本发布,而不是作为屏幕截图。 – nbrooks

+3

不要将您的代码发布为图片,发布代码! – Li357

+0

调用addLast的代码在哪里? – MikeJRamsey56

回答

0

给你的节点类的构造函数,将有助于保持你的代码短,干:

private class Node { 
    Item item; 
    Node next; 
    private Node(Item item, Node next) { 
    if (item == null) throw new NullPointerException(); 
// 'this' refers to the created instance and helps distinguish the field from the param 
    this.item = item; 
    this.next = next; 
    } 
} 

public void addFirst(Item item) { 
    // creates a new Node before first so to speak and then repoints first to this node 
    first = new Node(item, first); 
    if (num_elements==0) last = first; 
    num_elements++; 
} 

public void addLast(Item item) { 
    if (num_elements == 0) { 
    // this will deal with the case (last==null) which causes the NPE 
    addFirst(item); 
    return; 
    } 
    last.next = new Node(item, null); 
    last = last.next; 
    num_elements++; 
} 

这且不说,单链表是不是一个deque理想的数据结构。在两端添加的是O(1),从后面删除将是O(N)

+0

它的工作原理!非常感谢。但我对Java很新,所以我不太了解它是如何工作的。例如,我对这个类的构造函数感到困惑,尤其是在这个上下文中的关键字“this”。另外,对于addFirst()函数,为什么只需要first = new Node(item,first)而不是first.next = new Node(item,first)? –

+0

我添加了一些评论来说明这些观点。 'first.next = new Node(item,first)'会创建一个循环链接结构,不。 “first”是指新节点,新节点是指第一个。另外,'first'在这里可能为空,所以这可能会失败。 – schwobaseggl

+0

非常感谢你!另外,你能帮我解决另一个Java Comparator问题吗?我一直坚持这个很长一段时间!谢谢! http://stackoverflow.com/questions/40622793/having-trouble-implementing-a-nested-class-comparator –

1

你最后是null在第一。

当您将其分配给old_last时,old_last也为空。

所以当你拨打old_last.next,NPE就会丢。

+0

是的,这正是问题所在。那么你知道如何解决它吗?我知道你可以用一个单独的链表实现一个队列,并且为队列实现addLast()的代码和我的完全一样。那么为什么相同的实现适用于队列但不适用于双端队列呢? –

+0

检查http://codereview.stackexchange.com/questions/56361/generic-deque-implementation关于如何实现双端队列。 – Gearon