Stack Implementation (PUSH,POP & DISPLAY)

Posted: February 12, 2012 in Java Programs

WHAT IS IT ? : It is an collection of elements in which the elements can be inserted or deleted only at one known as top of stack. So it is similar to a pipe with one open end. The element inserted first will be removed last hence the concept of ‘LAST IN FIRST OUT’ and hence called LIFO structure.

Simple Java program to demonstrate working of stack.

import java.util.*;
class stack
{
static int a[]=new int[5];
static int top=0;
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println(” 1:PUSH \n 2:POP \n 3:DISPLAY \n 4:EXIT!”);
int n=sc.nextInt();
switch(n)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
System.exit(0);
break;
default:
System.out.println(“INVALID ENTRY”);
break;
}
}
}
static void push()
{
top++;
if(top>5)
{
System.out.println(“OVERFLOW!”);
}
else
{
System.out.println(“ENTER AN ELEMENT TO BE PUSHED ? “);
Scanner sc=new Scanner(System.in);
int b=sc.nextInt();
a[top]=b;
}
}
static void pop()
{
if (top==-1)
{
System.out.println(“Stack is underflowing !!!”);
}
else
{
int x=a[top];
top–;
System.out.println(“ELEMENT HAS BEEN POPPED : “+x);
}
}
static void display()
{
System.out.println(“Stack elements are :”);
for(int i=top;i>0;i–)
{
System.out.println(a[i]);
}
}
}

Advertisements
Comments
  1. Bhavesh Naik says:

    guys just make changes if you copy the program @ i– and top–
    đŸ™‚

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