import java.util.NoSuchElementException; public class QueueImpl<T> implements Qu
ID: 3817535 • Letter: I
Question
import java.util.NoSuchElementException;
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 in queue
private final int max = 100; // maximum number of elements in queue
// helper linked list class
private static class Node {
private Object item;
private Node next;
}
public static void main(String[] args){
}
/*initializes an empty queue
*
*/
public QueueImpl() {
first = null;
last = null;
n = 0;
}
/*returns true if this queue is empty
*
*/
public boolean isEmpty() {
return first == null;
}
/*returns the number of items in this queue
*
*/
public int size() {
return n;
}
@Override
public void enqueue(Object newEntry) {
if( n <= max){
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;
return (T) item;
}
@Override
public T getFront() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return (T) first.item;
}
@Override
public void clear() {
first = null;
last = null;
n = 0;
}
}
Explanation / Answer
class mains
{
public static void main(String []args)
{
Queueimpl obj=new Queueimpl;
obj.size();
obj.enqueue(obj);
obj.size();
obj.dequeue();
obj.getFront();
obj.clear();
}
this will tell the size of the queue and if want to insert some data then insert it
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.