How to implement stack in Java

0

 


In this blog we will how we can implement a stack using array.




class MyStack
{
int capacity;
int top;
int arr[];
MyStack(int capacity)
{
this.capacity=capacity;
this.top=-1;
this.arr=new int[capacity];
}
}
class ArrayImplementation
{
public static boolean isempty(MyStack stack)
{
if(stack.top==-1)
return true;
return false;
}
public static boolean isfull(MyStack stack)
{
if(stack.top==stack.capacity-1)
return true;
return false;
}
public static MyStack push(MyStack stack,int data)
{
if(isfull(stack)==true){
System.out.println("You can not push the values:");
return stack;}
else
{
stack.top=stack.top+1;
stack.arr[stack.top]=data;
return stack;
}
}
public static int pop(MyStack stack)
{
if(isempty(stack)==true){
System.out.println("You can not pop the values:");
return -1;}
else
{
int data=stack.arr[stack.top];
stack.top=stack.top-1;
return data;
}
}
public static void printStack(MyStack stack)
{
for(int i=0;i<=stack.top;i++)
System.out.print(stack.arr[i]+" ");
}
public static void main(String args[])
{
MyStack stack=new MyStack(10);
boolean b=isempty(stack);
System.out.println(b);

b=isfull(stack);
System.out.println(b);

stack=push(stack, 10);
stack=push(stack, 20);
stack=push(stack, 30);
stack=push(stack, 40);
int data=pop(stack);

System.out.println(data);
printStack(stack);
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !