MIT-Curricular/OOP/Java/Lab/Week5/Stack.java

112 lines
3.1 KiB
Java

import java.util.Scanner;
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full");
} else {
top++;
stackArray[top] = value;
}
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
return stackArray[top--];
}
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
return stackArray[top];
}
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
Stack stack = new Stack(5);
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\nStack Operations:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Check if empty");
System.out.println("5. Check if full");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value to push: ");
int value = sc.nextInt();
if (stack.isFull()) {
System.out.println(
"Cannot push anymore. Stack is full."
);
} else {
stack.push(value);
}
break;
case 2:
if (stack.isEmpty()) {
System.out.println("Cannot pop. Stack is empty.");
} else {
int poppedValue = stack.pop();
if (poppedValue != -1) {
System.out.println("Popped value: " + poppedValue);
}
}
break;
case 3:
int peekedValue = stack.peek();
if (peekedValue != -1) {
System.out.println("Top value: " + peekedValue);
}
break;
case 4:
System.out.println("Is stack empty? " + stack.isEmpty());
break;
case 5:
System.out.println("Is stack full? " + stack.isFull());
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
sc.close();
}
}