2016-12-01 110 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