📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
- 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: 20
Comments
Post a Comment
Leave Comment