data-structures/java/Queue/LQueue.java
2022-09-13 22:24:05 +05:30

45 lines
1.3 KiB
Java

/** Linked queue implementation */
class Lqueue<E> implements Queue<E> {
private Link<E> front; // Pointer to front queue node
private Link<E> rear; // Pointer to rear queue node
int size; // Number of elements in queue
/** Constructors */
public LQueue() { init(); }
public LQueue(int size) { init(); } // Ignore size
/** Initialize queue */
private void init() {
front = rear = new Link<E>(null);
size = 0;
}
/** Reinitialize queue */
private void clear() { init(); };
/** Put element on rear */
public void enqueue(E it) {
rear.setNext(new Link<E>(it, null));
rear = rear.next();
++size;
}
/** Remove and return element from front */
public E dequeue() {
assert size != 0 : "Queue is empty";
E it = front.next().element(); // Store dequeued value
front.setNext(front.next().next()); // Advance front
if (front.next() == null) rear = front; // Last object
--size;
return it; //Return object
}
/** @return Front element */
public E frontValue() {
assert size != 0 : "Queue is empty";
return front.next().element();
}
/** @return Queue size */
public int length() { return size; }
}