What Is Stack Data Structure?
A stack is a linear data structure in computer science that follows the Last-In-First-Out (LIFO) principle. It’s similar to a stack of plates where the last plate placed is the first one to be removed. In this article, we’ll explore the concept of a stack data structure and its various operations.
Stack Operations
Stacks have three primary operations:
- Push: This operation adds an element to the top of the stack.
- Pop: This operation removes and returns the element at the top of the stack.
- Peek: This operation returns the element at the top of the stack without removing it.
Additionally, there are two more auxiliary operations:
- isEmpty: This operation checks if the stack is empty, returning true or false accordingly.
- size: This operation returns the number of elements present in the stack.
The Stack Implementation
A stack can be implemented using arrays or linked lists. Here, we’ll discuss an array-based implementation since it’s a simpler and more commonly used approach.
We start by defining a fixed-size array and an integer variable called “top” that keeps track of the index of the topmost element in the stack. Initially, when no elements are present, we set “top” to -1.
class Stack {
private int maxSize; // maximum size of stack
private int[] stackArray; // array to store elements
private int top; // index of the topmost element
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1; // empty stack
}
public void push(int element) {
if (isFull()) {
System.out.println("Stack is full. Cannot push element.");
return;
}
stackArray[++top] = element;
}
public int pop() {
if (isEmpty()) {
System.println("Stack is empty. Cannot pop element.");
return -1;
}
return stackArray[top--];
}
public int peek() {
if (isEmpty()) {
System. No elements to peek.");
return -1;
}
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public int size() {
return top + 1;
}
}
Summary
In this article, we explored the concept of a stack data structure and its various operations. We discussed how stacks follow the Last-In-First-Out principle and covered operations like push, pop, peek, isEmpty, and size. Additionally, we provided an implementation example using arrays in Java.
Stacks are widely used in programming and have applications in areas such as function calls, expression evaluation, backtracking algorithms, and more. Understanding stacks is crucial for any aspiring programmer or computer science enthusiast.
Now that you have a good understanding of stack data structures, you can confidently use them to solve problems that require efficient handling of data.