1) Create a LLQueue class that implements the interface below. 2) The implementa
ID: 3813516 • Letter: 1
Question
1) Create a LLQueue class that implements the interface below.
2) The implementation must be a linked list-based.
3) The implementation must add a max capacity and must not allow users to add more elements to queue beyond it.
4) For this program use String objects as your testing data.
5) Add a Driver/Demo/Test class to test all the methods of LLQueue.
public interface QueueInterface<T>
{
/** Adds a new entry to the back of this queue.
@param newEntry An object to be added. */
public void enqueue(T newEntry);
/** Removes and returns the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty before the operation. */
public T dequeue();
/** Retrieves the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty. */
public T getFront();
/** Detects whether this queue is empty.
@return True if the queue is empty, or false otherwise. */
public boolean isEmpty();
/** Removes all entries from this queue. */
public void clear();
/** generates a string containing all data in the queue and returns it
public String toString();
} // end QueueInterface
Explanation / Answer
package com.chegg.test;
import java.util.NoSuchElementException;
import com.chegg.test.Queue.Node;
public class QueueImpl<T> implements QueueInterface<T> {
private Node first; // beginning of queue
private Node last; // end of queue
private int n; // number of elements on queue
// helper linked list class
private static class Node {
private Object item;
private Node next;
}
/**
* Initializes an empty queue.
*/
public QueueImpl() {
first = null;
last = null;
n = 0;
}
/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code false} otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {
return n;
}
@Override
public void enqueue(Object newEntry) {
Node oldlast = last;
last = new Node();
last.item = newEntry;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
}
@Override
public T dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Object item = first.item;
first = first.next;
n--;
if (isEmpty()) last = null; // to avoid loitering
return (T) item;
}
@Override
public T getFront() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return (T) first.item;
}
@Override
public void clear() {
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.