Friday, August 3, 2012

BlueJ program on stack and queue


In this program we will demonstrate stack and queue using an array. It’s a menu driven program. Here is the codes of the program

 import java.io.*;
class Enen
{
int f,r,n;
int arr[]=new int [10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take() throws Exception
{
f=-1;
r=-1;
System.out.println("\nEnter '1' for stack and '2' for Queue:");
n=Integer.parseInt(br.readLine());
if(n==1)
stack();
else
queue();
}
void queue()throws Exception
{
for(;;)
{
System.out.println("\nEnter '1' for push, '2' for pop and '3' for quit:");
n=Integer.parseInt(br.readLine());
if(n==3)
break;
else if(n==1)
queuePush();
else
queuePop();
}
}
 void stack()throws Exception
{
for(;;)
{
System.out.println("\nEnter '1' for push, '2' for pop and '3' for quit:");
n=Integer.parseInt(br.readLine());
if(n==3)
break;
else if(n==1)
stackPush();
else
stackPop();
}
}
private void queuePop()
{
if(f==-1 && r==-1)
System.out.println("\nQueue underflowing...");
else if(r==f)
{
System.out.println("\nDeleted element="+arr[f--]);
showQueue();
f=-1;
r=-1;
}
else {
System.out.println("\nDeleted element="+arr[f--]);
showQueue();
}
 }
 private void queuePush()throws Exception
{
if(r==10)
System.out.println("\nQueue overflowing...");
else
{
System.out.println("\nEnter value:");
arr[++r]=Integer.parseInt(br.readLine());
if(f==-1)
f=0;
showQueue();
}
}
private void showQueue()
{
 for(int i=f;i<=r;i++)
 System.out.print(" "+arr[i]);
 }
private void stackPop()
{
if(f==-1)
System.out.println("\nStack underflowing...");
else
{
System.out.println("\nDeleted element="+arr[f--]);
showStack();
}
}
 private void stackPush()throws Exception
{
if(f==10)
System.out.println("\nStack overflowing...");
else
{
System.out.println("\nEnter value:");
arr[++f]=Integer.parseInt(br.readLine());
showStack();
}
}
private void showStack()
{
 for(int i=f;i>=0;i--)
 System.out.print(" "+arr[i]);
 }
  public static void main(String args[]) throws Exception
{
 Enen ob=new Enen();
ob.take();
 }
}

Number of methods are used in this program. The first function ‘take()’ takes the decision as per user choice whether the program will be on stack or queue. The array ‘arr’ is used here to demonstrate the stack and queue program.

Stack uses only the front end while queue uses both ends. The variable ‘f’ is used to represent front end and ‘r’ is used to represent rare end. For stack the variable ‘f’ is used to insert, delete and display elements while in queue variable ‘r’ is used to represent the rare end and ‘f’ is used to represent front end. In queue, elements are inserted through the rear end and deleted from front end.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner