Stacks

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.
Properties
Section titled “Properties”- 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.
Use Cases
Section titled “Use Cases”- 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.
Operations
Section titled “Operations”- Push: Add element to the top of the stack.
- Pop: Remove and return the top element from the stack.
Advantages
Section titled “Advantages”- Simple and efficient operations: All basic operations have O(1) time complexity.
- Easy to implement: Simple structure makes implementation straightforward.
Disadvantages
Section titled “Disadvantages”- 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.
Example
Section titled “Example”import java.util.Stack;
Stack<String> students = new Stack<>();
// Push elements onto the stackstudents.push("Ashitosh");students.push("Eleanor");students.push("Othniel");
// Get stack sizeSystem.out.println(students.size()); // Prints 3
// Accessing the top elementSystem.out.println(students.peek()); // Prints "Othniel"
// Pop elements from the stackstudents.pop(); // Removes "Othniel", stack: [Ashitosh, Eleanor]students.pop(); // Removes "Eleanor", stack: [Ashitosh]System.out.println(students);