generic stack arraylist
Fri Jun 07 2024 12:44:47 GMT+0000 (Coordinated Universal Time)
Saved by @dbms
import java.util.ArrayList;
public class GenericStack<T> {
private ArrayList<T> stackList;
private int maxSize;
public GenericStack(int size) {
this.stackList = new ArrayList<>(size);
this.maxSize = size;
}
public void push(T item) {
if (stackList.size() < maxSize) {
stackList.add(item);
} else {
System.out.println("Stack Overflow");
}
}
public T pop() {
if (!stackList.isEmpty()) {
return stackList.remove(stackList.size() - 1);
} else {
System.out.println("Stack Underflow");
return null;
}
}
public boolean isEmpty() {
return stackList.isEmpty();
}
public boolean isFull() {
return stackList.size() == maxSize;
}
public T peek() {
if (!stackList.isEmpty()) {
return stackList.get(stackList.size() - 1);
} else {
return null;
}
}
public static void main(String[] args) {
GenericStack<Integer> intStack = new GenericStack<>(5);
intStack.push(1);
intStack.push(2);
intStack.push(3);
intStack.push(4);
intStack.push(5);
System.out.println("Stack is full: " + intStack.isFull()); // true
System.out.println("Top element: " + intStack.peek()); // 5
while (!intStack.isEmpty()) {
System.out.println("Popped element: " + intStack.pop());
}
System.out.println("Stack is empty: " + intStack.isEmpty()); // true
GenericStack<String> stringStack = new GenericStack<>(3);
stringStack.push("one");
stringStack.push("two");
stringStack.push("three");
System.out.println("Stack is full: " + stringStack.isFull()); // true
System.out.println("Top element: " + stringStack.peek()); // three
while (!stringStack.isEmpty()) {
System.out.println("Popped element: " + stringStack.pop());
}
System.out.println("Stack is empty: " + stringStack.isEmpty()); // true
}
}



Comments