//Queue impelementation using linked list and generics
interface QueueADT<E>
{
void enqueue(E data);
E dequeue();
E peek();
boolean isEmpty();
int size();
void traverse();
}
class QueueDemo
{
public static void main(String args[])
{
QueueImplementation<Integer> queue=new QueueImplementation<>();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.traverse();
System.out.println("\nQueue after deleting a element from front :");
queue.dequeue();
queue.traverse();
}
}
class Node<E>
{
private E data;
private Node<E> next;
public Node(E data)
{
this.data=data;
}
public void setData(E data)
{
this.data=data;
}
public E getData()
{
return data;
}
public void setNext(Node<E> next)
{
this.next=next;
}
public Node<E> getNext()
{
return next;
}
}
class QueueImplementation<E> implements QueueADT<E>
{
private Node<E> front;//head
private Node<E> rear;//tail
private int size;
public QueueImplementation()
{
front=null;
rear=null;
size=0;
}
public void enqueue(E element)//insert at last
{
Node<E> node=new Node<>(element);
if(!isEmpty())
{
rear.setNext(node);
rear=node;
}
else
{
front=node;
rear=node;
}
size++;
}
public E dequeue()//delete from first
{
E response=null;
if(!isEmpty())
{
response=front.getData();
front=front.getNext();
if(front==null)//when only single node in Queue and rear point to the first node
{
rear=null;
}
}
else
{
System.out.println("Queue is already empty you can't perform dequeue on it.");
}
size--;
return response;
}
public E peek()
{
E response=null;
if(!isEmpty())
{
response=front.getData();
}
return response;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
if(front==null)
{
return true;
}
else
{
return false;
}
}
public void traverse()
{
System.out.print("front"+"<----");
Node<E> temp=front;
while(temp!=null)
{
System.out.print(temp.getData()+" ");
temp=temp.getNext();
}
System.out.print("<----"+"rear");
}
}
0 Comments