2016-12-01 100 views
3

我在讀java隊列中的隊列。我發現下面的代碼隊列實現中的出隊和入隊方法

public class QueueOfStrings { 

    private Node first = null; // least-recently added 
    private Node last = null; // most-recently added 

    private class Node { 

     private String item; 
     private Node next; 
    } 

    // is the queue empty? 
    public boolean isEmpty() { 
     return first == null; 
    } 

    public String dequeue() { 
     if (isEmpty()) { 
      throw new RuntimeException("Queue underflow"); 
     } 
     String item = first.item; 
     first = first.next; 
     return item; 
    } 

    public void enqueue(String item) { 
     Node x = new Node(); 
     x.item = item; 
     if (isEmpty()) { 
      first = x; 
      last = x; 
     } else { 
      last.next = x; 
      last = x; 
     } 
    } 

我沒有改寫他們在我的方式是這樣的:

public String dequeue() { 
    if (isEmpty()) { 
     throw new RuntimeException("Queue underflow"); 
    } else if (first = last) { 
     String f = first.item; 
     first = null; 
     last = null; 
     return f; 
    } 

    String f = first.item; 
    first = first.next; 
    return f; 

} 
public void enqueue(String item) { 
    Node x = new Node(item); 
    if (first = last = null) { 
     first = last = x; 
    } 
    last.next = x; 
    last = x; 
} 

我在出隊右做()和排隊()方法?

在main方法,我應該這樣做:

public static void main(String[] args) { 

    QueueOfStrings q = new QueueOfStrings(); 
    q.enqueue("roro"); 
    q.enqueue("didi"); 
    q.enqueue("lala"); 

    System.out.println(q.dequeue()); 
} 

感謝

+0

是什麼意思爲 「我做的出隊))寫(和排隊(方法是什麼?」 ? - 另外,你的最後一個if應該是if(first == null && last == null){而不是if(first = last = null){ – matt

+0

我的意思是對的..我在其他代碼中發現它們有時使用'first = last = null' – Joe

+0

這甚至沒有編譯。你想用first = last = null做什麼? –

回答

3
public String dequeue() { 
    if (isEmpty()) { 
     throw new RuntimeException("Queue underflow"); 
    } else if (first == last) { 
     String f = first.item; 
     first = null; 
     last = null; 
     return f; 
    } 

    String f = first.item; 
    first = first.next; 
    return f; 

} 
public void enqueue(String item) { 
    Node x = new Node(item); 
    if (first == null && last == null) { 
     first = x; 
     last = x; 
     return; // return back when first node is enqueued 
    } 
    last.next = x; 
    last = x; 
} 
+0

@Joe當隊列爲空並且入列一個項時,它將直接進入'enqueue()'方法的'if'語句,對吧?如果你不放置'return'語句,代碼將繼續執行'if'語句之外的行。通過'return'我的意思是「該項目已經過帳,在這裏結束該方法,並返回到從」 – rafid059

+1

Rafiduzzaman Sonnet調用該方法的地方,但是當我刪除返回時,代碼運行良好,即使第一個和最後一個null,謝謝 – Joe

+0

@Joe刪除'return'語句也可以,但它更具可讀性。同樣,如果你刪除return語句,當你排隊第一個項目時,在方法結束時它會指向它自己(當你排隊第二個項目時它會被修復,但這是你不想要的行爲)。所以,比對不起更安全 – rafid059