Skip to content

Stacks

This content is for DSA. Switch to the latest version for up-to-date documentation.

Image

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, meaning the last element added is the first one to be removed. Think of it like a stack of plates - you can only add or remove plates from the top of the stack.

  • LIFO (Last In, First Out) ordering: The most recently added element is the first one to be removed.
  • Access only to top element: You can only interact with the element at the top of the stack.
  • Limited access pattern: No random access to elements in the middle of the stack.
  • Dynamic size: Can grow and shrink as elements are added or removed.
  • Undo operations: Stacks are used to keep track of previous states, allowing you to undo actions in applications.
  • Browser back button: Web browsers use stacks to remember the sequence of pages visited, enabling you to go back to previous pages.
  • Push: Add element to the top of the stack.
  • Pop: Remove and return the top element from the stack.
  • Simple and efficient operations: All basic operations have O(1) time complexity.
  • Easy to implement: Simple structure makes implementation straightforward.
  • Limited access: Only the top element can be accessed directly, no random access to elements.
  • Can overflow: If size limit exceeded (in array-based implementations), stack overflow can occur.
import java.util.Stack;
Stack<String> students = new Stack<>();
// Push elements onto the stack
students.push("Ashitosh");
students.push("Eleanor");
students.push("Othniel");
// Get stack size
System.out.println(students.size()); // Prints 3
// Accessing the top element
System.out.println(students.peek()); // Prints "Othniel"
// Pop elements from the stack
students.pop(); // Removes "Othniel", stack: [Ashitosh, Eleanor]
students.pop(); // Removes "Eleanor", stack: [Ashitosh]
System.out.println(students);
Built with passion by Ngineer Lab