Stack
Stack
int size,top=-1;
int [] array;
public Stack(int size){
this.size=size;
array = new int[size];
}
void push(int ele){
if(top>size){
System.out.println("Array is over flow.");
}
else{
top++;
array[top]=ele;
}
}
public int pop(){
if(top<0){
System.out.println("Array is underflow");
return -1;
}
else{
return array[top--];
}
}
int peek(){
return array[top];
}
boolean isEmpty(){
return(top == -1);
}
String display(){
String print = "[";
for(int i=0;i<size;i++){
print+=array[i]+" ";
}
print+="]";
return print;
}
}
class Main{
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(4);
stack.push(2);
stack.push(3);
stack.push(1);
stack.push(16);
System.out.println("Size of stack: "+stack.size);
System.out.println("Top element: "+stack.peek());
System.out.println("Pop element: "+stack.pop());
System.out.println("Is stack empty: "+stack.isEmpty());
System.out.println("Array: "+stack.display());
}
}