A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. One of the simplest ways to implement a stack is by using an array. An array stores elements in a continuous sequence of indexed positions, while a stack allows insertion and deletion only from the top. In this article, you will learn how to implement a stack using an array, understand its basic operations, and explore its advantages, limitations, and JavaScript examples.
Table of Contents
What Is a Stack Using an Array?
A stack using an array is a stack implementation in which elements are stored in an array and accessed according to the LIFO principle.
In this implementation, an array stores the stack elements, and a variable called top keeps track of the index of the top element.
Initially, the stack is empty, so top is set to -1. Whenever an element is inserted, the value of top is increased. When an element is removed, top is decreased.
For example, if the elements 10, 20, and 30 are inserted into a stack, the element 30 becomes the top element and will be removed first.
How Does a Stack Using an Array Work?
A stack using an array works by maintaining a variable called top to track the most recently inserted element.
The following steps explain its working:
- Create an array to store stack elements.
- Initialize the top variable to -1.
- Use the push operation to insert elements.
- Increase top whenever a new element is inserted.
- Use the pop operation to remove the top element.
- Decrease top whenever an element is removed.
- Check whether the stack is empty or full before performing operations.
The top variable helps the program identify where the next insertion or removal should take place.
Basic Operations of Stack Using Array
A stack implemented using an array supports several basic operations.
1. Push Operation
The push operation inserts a new element at the top of the stack.
Before inserting an element, the program checks whether the stack has reached its maximum capacity. If the stack is full, stack overflow occurs.
2. Pop Operation
The pop operation removes the top element from the stack.
Before removing an element, the program checks whether the stack is empty. If no elements are available, stack underflow occurs.
3. Peek Operation
The peek operation returns the top element without removing it from the stack.
4. isEmpty Operation
The isEmpty operation checks whether the stack contains any elements. If top is equal to -1, the stack is empty.
5. isFull Operation
The isFull operation checks whether the stack has reached its maximum capacity. If top is equal to size - 1, the stack is full.
6. Display Operation
The display operation prints all elements currently stored in the stack, starting from the top and moving toward the bottom.
Stack Using Array Implementation in JavaScript
The following JavaScript program demonstrates how to implement a stack using an array.
// Implement a stack using an array and perform basic stack operations.
class Stack {
constructor(size) {
this.items = new Array(size);
this.top = -1;
this.size = size;
}
push(element) {
if (this.top === this.size - 1) {
console.log("Stack Overflow");
return;
}
this.top++;
this.items[this.top] = element;
console.log(element + " inserted");
}
pop() {
if (this.top === -1) {
console.log("Stack Underflow");
return;
}
const removed = this.items[this.top];
this.top--;
console.log(removed + " removed");
}
peek() {
if (this.top === -1) {
console.log("Stack is Empty");
return;
}
console.log("Top element: " + this.items[this.top]);
}
isEmpty() {
return this.top === -1;
}
isFull() {
return this.top === this.size - 1;
}
display() {
if (this.isEmpty()) {
console.log("Stack is Empty");
return;
}
console.log("Stack elements:");
for (let i = this.top; i >= 0; i--) {
console.log(this.items[i]);
}
}
}
const stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
stack.display();
stack.peek();
stack.pop();
stack.display();
console.log("Is Empty:", stack.isEmpty());
console.log("Is Full:", stack.isFull());
Output:
10 inserted
20 inserted
30 inserted
Stack elements:
30
20
10
Top element: 30
30 removed
Stack elements:
20
10
Is Empty: false
Is Full: false
Explanation:
In this example, a stack is created with a maximum capacity of five elements.
- The constructor initializes an array and sets top to -1.
- The push operation inserts 10, 20, and 30 into the stack.
- The display operation prints elements from top to bottom.
- The peek operation returns 30 without removing it.
- The pop operation removes 30 from the stack.
- The isEmpty operation checks whether the stack is empty.
- The isFull operation checks whether the stack has reached its maximum capacity.
This implementation uses an array and a top variable to perform stack operations.
Example of Stack Using Array
Consider a stack with a maximum capacity of four elements.
The following JavaScript program demonstrates insertion and deletion operations.
// Demonstrate push and pop operations in an array-based stack.
const stack = [];
const maxSize = 4;
function push(element) {
if (stack.length >= maxSize) {
console.log("Stack Overflow");
return;
}
stack.push(element);
console.log(element + " inserted");
}
function pop() {
if (stack.length === 0) {
console.log("Stack Underflow");
return;
}
console.log(stack.pop() + " removed");
}
push(10);
push(20);
push(30);
push(40);
push(50);
pop();
pop();
Output:
10 inserted
20 inserted
30 inserted
40 inserted
Stack Overflow
40 removed
30 removed
Explanation:
In this example, the stack can store a maximum of four elements.
- The first four push operations successfully insert elements.
- The fifth push operation tries to insert 50, but the stack is full.
- Therefore, the program displays "Stack Overflow".
- The first pop operation removes 40.
- The second pop operation removes 30.
This example demonstrates how an array can be used to perform stack operations while checking for overflow and underflow conditions.
Time Complexity of Stack Operations
The time complexity of stack operations using an array is generally efficient because elements are inserted and removed from the top.
| Operation | Time Complexity | Description |
|---|---|---|
| Push | O(1) | Inserts an element at the top. |
| Pop | O(1) | Removes the top element. |
| Peek | O(1) | Accesses the top element. |
| isEmpty | O(1) | Checks whether the stack is empty. |
| isFull | O(1) | Checks whether the stack is full. |
| Display | O(n) | Visits all elements in the stack. |
Here, n represents the number of elements in the stack.
Advantages of Stack Using Array
Implementing a stack using an array provides several benefits.
- Simple Implementation: Arrays make it easy to create and manage a stack.
- Fast Operations: Push, pop, and peek operations generally take O(1) time.
- Easy Access to the Top: The top variable provides direct access to the top element.
- Memory Efficiency: No extra pointer is required for each element, unlike a linked-list implementation.
- Contiguous Storage: Array elements are stored in indexed positions, which can provide good memory locality.
Limitations of Stack Using Array
Although an array-based stack is useful, it also has some limitations.
- Fixed Capacity: A fixed-size array cannot store more elements than its allocated capacity.
- Stack Overflow: Inserting an element into a full stack causes an overflow condition.
- Possible Memory Waste: Allocating a large array may leave some positions unused.
- Resizing Requirements: Increasing the capacity of a fixed-size array requires creating a larger array and copying existing elements.
- Limited Access: Only the top element is directly available through normal stack operations.
Common Mistakes to Avoid
-
Incorrect Top Initialization: Always initialize top to -1 when the stack is empty.
-
Ignoring Stack Overflow: Check whether the stack is full before inserting a new element into a fixed-size array.
-
Ignoring Stack Underflow: Check whether the stack is empty before performing the pop operation.
-
Updating Top Incorrectly: Increase top after confirming that insertion is possible and decrease it only after a successful removal.
-
Confusing Array Index with Stack Size: Remember that an array of size n has valid indexes from 0 to n - 1.
Frequently Asked Questions
1. What is a stack using an array?
A stack using an array is a linear data structure implementation in which elements are stored in an array and accessed according to the LIFO principle.
2. Why is the top variable initialized to -1?
The top variable is initialized to -1 because an empty array-based stack does not contain any valid element index.
3. What is the time complexity of push and pop operations?
Both push and pop operations generally take O(1) time because they insert or remove elements directly at the top.
4. What happens when an array-based stack becomes full?
If a fixed-size stack is full and another element is inserted, a stack overflow condition occurs.
5. Can a stack be implemented using a dynamic array?
Yes. A stack can be implemented using a dynamic array that automatically increases its capacity when additional elements are required. JavaScript arrays can also grow dynamically when elements are added using the push() method.
0 Comments