Sobes.tech
Intern

What are stacks?

sobes.tech AI

Answer from AI

A stack is a data structure that operates on the Last-In, First-Out (LIFO) principle. Elements are added and removed only from one end, called the top of the stack.

Main operations:

  • push: add an element to the top of the stack.
  • pop: remove the top element from the stack and return it.
  • peek: view the value of the top element without removing it.
  • isEmpty: check if the stack is empty.

In Java, the stack is represented by the Stack class, which is a subclass of Vector.

// Example of using Stack
import java.util.Stack;

public class StackExample {

    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();

        stack.push("First"); // Adding elements
        stack.push("Second");
        stack.push("Third");

        System.out.println("Top of the stack: " + stack.peek()); // View the top element

        while (!stack.empty()) { // While the stack is not empty
            System.out.println("Extracting: " + stack.pop()); // Remove elements
        }
    }
}

An alternative and more recommended approach in modern Java development is to use ArrayDeque as a stack, as it provides better performance.

// Example of using ArrayDeque as a stack
import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeStackExample {

    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>(); // Using Deque as a stack

        stack.push("First"); // Adding elements
        stack.push("Second");
        stack.push("Third");

        System.out.println("Top of the stack: " + stack.peek()); // View the top element

        while (!stack.isEmpty()) { // While the stack is not empty
            System.out.println("Extracting: " + stack.pop()); // Remove elements
        }
    }
}

Applications of stacks:

  • Evaluating arithmetic expressions (e.g., in Reverse Polish Notation).
  • Undo/redo operations in editors (Ctrl+Z/Ctrl+Y).
  • Managing function calls in the operating system.
  • Recursive algorithms.
  • Graph and tree traversal (depth-first search).