Junior — Middle
How can a Stack data structure be implemented in programming?
sobes.tech AI
Answer from AI
A stack is a data structure that operates on the LIFO (Last In, First Out) principle, meaning the last added element is the first to be removed.
In Android (Java/Kotlin), a stack can be implemented in several ways:
- Using the
Stackclass from Java Collections:
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
stack.push(10); // Add element
int top = stack.pop(); // Remove the top element
- Using
Dequeas a stack (preferred method):
import java.util.ArrayDeque;
import java.util.Deque;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10); // Add element
int top = stack.pop(); // Remove the top element
- Implementing a stack manually using a list:
import java.util.ArrayList;
public class MyStack<T> {
private ArrayList<T> list = new ArrayList<>();
public void push(T item) {
list.add(item);
}
public T pop() {
if (list.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return list.remove(list.size() - 1);
}
public boolean isEmpty() {
return list.isEmpty();
}
}
Thus, a stack can be implemented either using ready-made Java classes or manually using a list and add/remove methods at the end of the collection.