package Stack;
public class Stack_Array {
int[] arr;
int topOfStack;
//Create Stack TC:O(1) SC:O(N)
public Stack_Array(int size) {
this.arr = new int[size];
this.topOfStack = -1;
System.out.println("The stack is created with size of: " +
size);
}
//isEmpty TC:O(1) SC:O(1)
public boolean isEmpty() {
if (topOfStack == -1) {
return true;
} else {
return false;
}
}
//isFull
public boolean isFull() {
if (topOfStack == arr.length - 1) {
System.out.println("The Stack is full! ");
return true;
} else {
return false;
}
}
// PUSH TC:O(1) SC:O(1)
public void push(int value) {
if (isFull()) {
System.out.println("The stack is full! ");
} else {
arr[topOfStack + 1] = value;
topOfStack++;
System.out.println("The value is successfully inserted
" + value);
}
}
//pop TC:O(1) SC:O(1)
public int pop() {
if (isEmpty()) {
System.out.println("The stack is empty ");
return -1;
} else {
int topStack = arr[topOfStack];
topOfStack--;
return topStack;
}
}
// Peek Method TC:O(1) SC:O(1)
public int peek() {
if (isEmpty()) {
System.out.println("The Stack is empty ");
return -1;
} else {
return arr[topOfStack];
}
}
// Delete method TC:O(1) SC:O(1)
public void deleteStack() {
arr = null;
System.out.println("The stack is successfully deleted ");
}
public static void main(String[] args) {
Stack_Array sa = new Stack_Array(4);
boolean result = sa.isEmpty();
System.out.println(result);
boolean result1 = sa.isFull();
System.out.println(result1);
sa.push(1);
sa.push(2);
sa.push(3);
sa.push(4);
int result3 = sa.pop();
System.out.println("The pop element is: " + result3);
int result4 = sa.peek();
System.out.println("The peek element is: " + result4);
sa.deleteStack();
}
}
OUTPUT: