Array Stack

// Array based Stack

import java.io.*;
public class array_stack
{
int top, max;
int stk[];

array_stack(int m)
{
max=m;
stk=new int[max];
top=-1;
}

public static void main() throws IOException
{
BufferedReader y = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter the stack size”);
int s=Integer.parseInt(y.readLine());

array_stack obj=new array_stack(s);
int cont;
int c,x;

do
{
System.out.println(“1. Push”);
System.out.println(“2. Pop”);
System.out.println(“3. Display”);
System.out.println(“4. Peep”);
System.out.println(“5. Quit”);
System.out.println(“Enter ur choice ?”);
c=Integer.parseInt(y.readLine());

switch(c)
{
case 1:
System.out.println(“Enter the new element to be pushed”);
x=Integer.parseInt(y.readLine());
obj.push(x);
break;

case 2:
obj.pop();
break;

case 3:
obj.display();
break;

case 4:
System.out.println(“The top most element is : “+ obj.stk[obj.top]);
break;

case 5:
System.out.println(“TERMINATING JAVA VIRTUAL MACHINE….”);
System.exit(0);

default:
System.out.println(“Wrong choice… Re enter your choice”);
}

System.out.println(“Press 1 to continue and any other number to terminate…”);
cont=Integer.parseInt(y.readLine());

} while(cont==1);

System.out.println(“TERMINATING JAVA VIRTUAL MACHINE….”);
System.exit(0);
}

public void push(int x)
{
if(top>=max-1)
System.out.println(“Stack overflow…”);
else
{
top++;
stk[top]=x;
}
}

public void pop()
{
if(top==-1)
System.out.println(“Stack underflow…”);

else
{
System.out.println(“Element deleted from the stack : “+stk[top]);
top–;
}

}

public void display()
{
int i;
System.out.println(“TOP”);
for(i=top;i>=0;i–)
{
System.out.println(stk[i]);
}
System.out.println();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s