Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dequeue and enqueue methods in queue implementation

Tags:

java

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

like image 729
Joe Avatar asked Dec 01 '16 13:12

Joe


1 Answers

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;
}
like image 151
denvercoder9 Avatar answered Oct 13 '22 03:10

denvercoder9