Program to Stack implementation using array in Java :
Copy this code and run in your computer
-----------------------------------------------------------------------------------------------------------------------------
//Stack implementation using array in java programming
interface StackADT
{
void push(int element);
int pop();
int peek();
boolean isEmpty();
int size();//top+1
}
//implemention
class MyStack implements StackADT
{
//maximum number of elements in stack
private final int MAX_CAPACITY;
//to store elements of stack
private int[] arr;
//top
int top;
public MyStack(int MAX_CAPACITY)
{
this.MAX_CAPACITY=MAX_CAPACITY;
//construct an array
arr=new int[MAX_CAPACITY];
top=-1;
}
//@override
public boolean isEmpty()
{
// return top==-1;
if(top==-1)
{
return true;
}
else
{
return false;
}
}
//@override
public void push(int element)
{
if(top!=MAX_CAPACITY-1)
{
// if stack is not full
top++;
arr[top]=element;
System.out.println("Element inserted.");
}
else
{
System.out.println("Stack Overflow.");
}
}
//@override
public int pop()
{
int res=0;
if(!isEmpty())
{
//stack is not empty
res=arr[top];
top--;
}
else
{
System.out.println("Stack Underflow.");
}
return res;
}
//@override
public int peek()
{
int res=0;
if(!isEmpty())
{
res=arr[top];
}
else
{
System.out.println("Stack is empty.");
}
return res;
}
//@override
public int size()
{
return top+1;
}
public void traverse()
{
for(int i=0; i<=top; i++)
{
System.out.print(arr[i]+", ");
}
System.out.println();
}
public boolean search(int searchElement)
{
boolean res=false;
for(int i=0; i<=top; i++)
{
if(arr[i]==searchElement)
{
res=true;
break;
}
}
return res;
}
}
class Jeev
{
public static void main(String args[])
{
//capacity of stack
int capacity=5;
//create stack, by creating instance of MyStack2
MyStack stack=new MyStack(capacity);
stack.pop();
stack.peek();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Size of stack :"+stack.size());
stack.push(40);
stack.push(50);
stack.push(60);
stack.traverse();
System.out.println("Searching 40 in stack, found ="+stack.search(40));
}
}
-----------------------------------------------------------------------------------------------------------------------------
Expected Output :
0 Comments