队列实现中的队列出队和入队

时间:2016-12-01 13:44:53

标签: java

我正在阅读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;
}

我在dequeue()和enqueue()方法中做得对吗?

在主要方法中我应该这样做:

public static void main(String[] args) {

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

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

由于

1 个答案:

答案 0 :(得分:4)

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;
}