Joe Joe - 8 days ago 6
Java Question

dequeue and enqueue methods in queue implementation

I was reading about queues in java implementation. I found the following code

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


I did rewrite them in my way like this:

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


Am I doing right in dequeue() and enqueue() methods?

In the main method should I do like this:

public static void main(String[] args) {

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

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


Thanks

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