2017-02-10 52 views
0

我在C++中基本上没有链接列表的问题,但是出于某种原因,这会让我感到困惑。我使用提供的包中的其他类打印出单个节点,但是随着我继续往下走,我只是一直跑到墙上。如何调试我的Java链接列表队列?

下面的代码是由于我的修补而引起的混乱。我不知道该从哪里出发。截至目前,这是获得空指针例外。

仅供参考:poll()只是删除当前的头部并返回它,offer()正在添加到后方。截至目前,报价方法中的例外情况为oldLast.next = last

我不是要求任何人完全解决这个问题。我只是需要一些提示来进步。

public class FIFOQueue implements Queue { 

//put your name as the value of the signature. 
String signature = "name"; 

Node head = new Node(null); 
Node pointer = head; 
Node first; 
Node last; 
Node prev; 
Node curr; 

class Node { 
    Process process; 
    Node next; 


    Node(Process p) { 
     this.process = p; 
     this.next = null; 
    } 

} 

@Override 
public void offer(Process p) { 


    if(head == null) 
    { 
     head = new Node(p); 
     first = head; 
     last = head; 

    } 

    else 
    { 

     Node oldLast = last; 
     Node newNode = new Node(p); 

     last = newNode; 
     oldLast.next = last; 


    } 



} 


@Override 
public Process poll() { 


    if(isEmpty()) 
     throw new NoSuchElementException(); 

    Node oldPointer = first; 

    first = first.next; 
    head = first; 


     return oldPointer.process; 
} 

@Override 
public boolean isEmpty() { 

return head == null; 

} 

@Override 
public String getSignature() { 
    return signature; 
} 

} 
+1

你需要更具体。如果你说“我在第15行有一个ArrayIndexOutOfBoundsException”而不是“事情不能工作,我希望你能帮助我”,那么你更有可能得到答案。 – Kayaman

+0

真的够了,对不起。截至目前,我正在从“\t \t \t oldLast.next = last;”中得到例外。在报价功能中。 – Clannadqs

+0

如果你从那里得到一个'NPE',那么你的'oldLast'就是null。无论何时出现'NullPointerException',请参阅http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it。 – Kayaman

回答

0

我觉得你的核心问题是在这里:

Node prev; 
Node curr; 

这些迷惑你。删除它们。

  1. Node prev; - 这应该在Node类中。
  2. Node curr; - 这应该是一个局部变量,而不是一个实例变量。

而且

Node head = new Node(null); 

if(head == null) 
{ 
    head = new Node(p); 

凝胶要么使head == null意味着列表为空或别的东西 - 而且是一致的。

+0

我不相信我也用过。这是一项正在进行的工作,我正在琢磨一下,看看有没有什么工作。使用这两个变量是我的下一个举措。我到目前为止只宣布他们。 – Clannadqs

+0

醒来,看到你的编辑。谢谢你回到我身旁。我对这两个人如何不排队感到困惑。应该保持空白? – Clannadqs

+0

您的评论基本上帮助我解决了我的问题。发现初始检查应该是查看节点中的实际数据是否为空,而不是检查整个节点是否为空。谢谢! – Clannadqs

0

(发表于OP)

public void offer(Process p) { 


    if(head.process == null) 
    { 
     head = new Node(p); 
     first = head; 
     last = head; 
    } 


     last.next = new Node(p); 
     last = last.next; 

} 

这解决了我的问题。不能相信我让我迷惑。