2017-02-10 109 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; 

} 

這解決了我的問題。不能相信我讓我迷惑。