- Stack Implementation using Array in Java
- Dynamic Stack Implementation using Array in Java
- Stack Implementation using Linked List in Java
Why an ArrayList?
Stack Implementation using Array List in Java
import java.util.ArrayList;
public class StackUsingArrayList<T> {
private ArrayList<T> stackList;
// Constructor to initialize the stack
public StackUsingArrayList() {
stackList = new ArrayList<>();
}
// Function to check if the stack is empty
public boolean isEmpty() {
return stackList.isEmpty();
}
// Function to push an element onto the stack
public void push(T value) {
stackList.add(value);
}
// Function to pop an element from the stack
public T pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return null;
}
return stackList.remove(stackList.size() - 1);
}
// Function to get the top element of the stack without popping it
public T peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return null;
}
return stackList.get(stackList.size() - 1);
}
}public class Main {
public static void main(String[] args) {
StackUsingArrayList<Integer> stack = new StackUsingArrayList<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek()); // Outputs: 30
System.out.println("Popped element: " + stack.pop()); // Outputs: 30
System.out.println("Top element after pop: " + stack.peek()); // Outputs: 20
}
}Top element: 30
Popped element: 30
Top element after pop: 20Conclusion
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment