Design an interface named Queue with the following methods:
(a) Insert and Delete elements from the Queue.
(b) check whether the Queue is empty or not.
Implement the queue with the help of arrays and if the size of the array becomes too small to hold Java the elements, create a new one. Test this interface by inheriting it in its subclass Queuetest.java.
Program:
import java.util.Scanner;
interface Queue
{
void display();
void insert();
int delete();
}
class Queue1 implements Queue{
Scanner sc=new Scanner(System.in);
int f=-1,r=-1;
int q[]=new int[5];
public void insert()
{
int num;
if(r>=q.length-1)
{
System.out.println("Queue is overflow..");
}
else
{
System.out.println("Enter Number...");
num=sc.nextInt();
r=r+1;
q[r]=num;
if(f==-1)
f=0;
}
}
public int delete()
{
int val;
if(f==-1)
{
System.out.println("Queue is Underflow");
return -1;
}
val=q[f];
if(f==r)
{
f=r=-1;
}
else
{
f=f+1;
}
return val;
}
public void display()
{
int i;
for(i=f;i<=r;i++)
{
System.out.println(q[i]);
}
}
}
class QueueTest{
public static void main(String ag[]){
Scanner sc=new Scanner(System.in);
Queue1 k=new Queue1();
int ch,p,f=-1,r=-1;
do{
System.out.println("===MENU===");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("0. Exit");
System.out.println("Enter Choice:= ");
ch=sc.nextInt();
if(ch==1)
{
k.insert();
}
else if(ch==2)
{
p=k.delete();
if(f==0 && r==0)
{
System.out.println("Queue is Underflow");
}
else
{
System.out.println("Delete Element "+p);
}
}
else if(ch==3)
{
k.display();
}
else if(ch==4)
{
System.out.println("Good Bye");
}
}while(ch!=0);
}
}
No comments:
Post a Comment