stack example in java
Stack:-stack used in data structure to insert and delete element from top.
LIFO:-Last In First Out.
Following example illustrate Stack.
class MyStack {
private int SIZE;
private int top=-1;
private int[] arr;
MyStack()
{
SIZE=5;
arr=new int[5];
}
MyStack(int SIZE)
{
this.SIZE=SIZE;
arr=new int[SIZE];
}
//empty method
public boolean isEmpty()
{
return top==-1;
}
//full method
public boolean isFull()
{
return top==SIZE-1;
}
//push method
public void push(int num)
{
if(isFull())
{
System.out.println("push perform on full Stack");
}
else
{
top++;
arr[top]=num;
System.out.println(num+" is pushed");
}
}
//pop method
public int pop()
{
if(isEmpty())
{
System.out.println("pop perform on empty stack");
return -000;
}
else
{
int x=arr[top];
top--;
System.out.println(x+" is pop");
return x;
}
}
}
class TestStack
{
public static void main (String args[])
{
MyStack S=new MyStack(5);//stack of size 5.
S.pop();
//pushing 4 element
S.push(1);
S.push(2);
S.push(3);
S.push(4);
S.push(5);
S.push(6);
//Popping value
S.pop();
S.pop();
S.pop();
S.pop();
S.pop();
S.pop();
}
}
LIFO:-Last In First Out.
Following example illustrate Stack.
class MyStack {
private int SIZE;
private int top=-1;
private int[] arr;
MyStack()
{
SIZE=5;
arr=new int[5];
}
MyStack(int SIZE)
{
this.SIZE=SIZE;
arr=new int[SIZE];
}
//empty method
public boolean isEmpty()
{
return top==-1;
}
//full method
public boolean isFull()
{
return top==SIZE-1;
}
//push method
public void push(int num)
{
if(isFull())
{
System.out.println("push perform on full Stack");
}
else
{
top++;
arr[top]=num;
System.out.println(num+" is pushed");
}
}
//pop method
public int pop()
{
if(isEmpty())
{
System.out.println("pop perform on empty stack");
return -000;
}
else
{
int x=arr[top];
top--;
System.out.println(x+" is pop");
return x;
}
}
}
class TestStack
{
public static void main (String args[])
{
MyStack S=new MyStack(5);//stack of size 5.
S.pop();
//pushing 4 element
S.push(1);
S.push(2);
S.push(3);
S.push(4);
S.push(5);
S.push(6);
//Popping value
S.pop();
S.pop();
S.pop();
S.pop();
S.pop();
S.pop();
}
}
OUTPUT
Comments
Post a Comment