Sobes.tech
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:

  1. Using the Stack class 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
  1. Using Deque as 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
  1. 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.

How can a Stack data structure be implemented in… - sobes.tech