0% completed
The Stack
class in Java represents a last-in, first-out (LIFO) data structure. It is part of the Java Collections Framework and extends the Vector
class, which means it inherits all the behaviors of a dynamic array while adding stack-specific methods.
A stack operates on the principle that the most recently added element is the first one to be removed. This behavior is particularly useful in scenarios such as undo mechanisms, parsing expressions, and backtracking algorithms.
LIFO Principle:
Elements are pushed onto the top of the stack and popped from the top. The last element added is the first one removed.
Inherits from Vector:
Since Stack
extends Vector
, it supports all methods of the Vector
class. However, it also provides additional methods specific to stack operations.
Common Stack Operations:
import java.util.Stack; Stack<Type> stack = new Stack<Type>();
Stack
that holds objects of the specified Type
. Since Stack
implements the List interface (through Vector
), it supports both generic and stack-specific methods.In this example, we create a Stack
of strings and demonstrate basic operations: pushing elements onto the stack, peeking at the top element, popping elements off the stack, and checking if the stack is empty.
Example Explanation:
peek()
retrieves the top element ("Third") without removing it.pop()
removes and returns the top element. The first two pops remove "Third" and "Second".empty()
method is used to check if the stack has any elements remaining.This example demonstrates the use of the search()
method. The search()
method returns the 1-based position of an element from the top of the stack, or -1 if the element is not found.
Example Explanation:
search(20)
method returns the 3rd position from the top (1-based), indicating that the element 20 is found.search(50)
returns -1 because 50 is not in the stack.search()
method can be used to locate elements within a stack.Understanding the Stack class is fundamental for implementing LIFO-based algorithms and managing tasks that require reverse-order processing.
.....
.....
.....