Introduction to Stacks
A stack is a fundamental data structure in computer science that follows the Last-In, First-Out (LIFO) principle. It is an ordered collection of elements where the addition of new elements and the removal of existing elements occur at the same end. This end is commonly referred to as the top of the stack.
Stacks are heavily used in programming for various purposes, including function calls, expression evaluation, history tracking, and more. They provide an efficient way to manage data in certain scenarios.
Basic Properties of Stacks
Here are some key properties of stacks:
LIFO Ordering: Stacks follow the LIFO ordering, which means that the last element added to the stack will be the first one to be removed.
Two Fundamental Operations: Stacks support two fundamental operations:
- Push: Adds an element to the top of the stack.
- Pop: Removes and returns the top element from the stack. If the stack is empty, an error may occur.
Peek/Top: Retrieves the top element of the stack without removing it.
Implementation of Stacks
There are several ways to implement a stack, including using arrays, linked lists, or dynamic arrays. Each implementation has its own advantages and disadvantages depending on the specific use case.
Array-Based Stack
An array-based stack uses a fixed-size array to store the elements. The top of the stack is tracked using an index variable that points to the last inserted element. When the stack is full, it cannot accommodate additional elements. This implementation provides constant-time complexity for the push and pop operations.
Linked List-Based Stack
A linked list-based stack uses a linked list to store the elements. Each node in the linked list represents an element, and the top of the stack is represented by the head of the linked list. This implementation allows for dynamic resizing and can accommodate an arbitrary number of elements. However, it requires additional memory to store the references of the nodes.
Example
Let's take a look at an example Java code that demonstrates the basic operations of a stack:
xxxxxxxxxx
}
class Main {
public static void main(String[] args) {
// Create an empty stack
Stack<Integer> stack = new Stack<>();
// Push elements into the stack
stack.push(5);
stack.push(10);
stack.push(15);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
// Get the size of the stack
int size = stack.size();
// Peek at the top element of the stack
int topElement = stack.peek();
// Pop an element from the stack
int poppedElement = stack.pop();
// Print the elements
System.out.println("Stack: " + stack);
System.out.println("Is Empty: " + isEmpty);
System.out.println("Size: " + size);
System.out.println("Top Element: " + topElement);
System.out.println("Popped Element: " + poppedElement);
}