Stack Implementation Using Array
What is Stack implementation using array?
A stack is a linear data structure that follows the LIFO (Last In First Out) principle. Arrays provide a simple way to implement stack operations with constant time complexity.
Core Stack Operations
push(item)
pop()
peek()
isEmpty()
isFull()
Algorithmic Steps
Stack Basic Operations
Initialize Stack
- Create an empty array to store elements
- Initialize top pointer/index to -1
- Optional: Set maximum size limit
push()
- Check if stack is full
- If full, return "Stack Overflow"
- Increment top pointer
- Store element at array[top]
pop()
- Check if stack is empty
- If empty, return "Stack Underflow"
- Access element at array[top]
- Decrement top pointer
- Return the element
Stack Helper Operations
peek()
- Check if stack is empty
- If empty, return null
- Return array[top] without removal
isEmpty()
- Return true if top pointer is -1
- Return false otherwise
isFull()
- Return true if top equals (max_size - 1)
- Return false otherwise
Visual Representation
42
17
8 (top)
Stack after operations: push(42), push(17), push(8)
Time Complexity
Operation | Complexity |
---|---|
push() | O(1) |
pop() | O(1) |
peek() | O(1) |
isEmpty() | O(1) |
Key Characteristics
- *LIFO Principle: Last element added is first removed
- *Dynamic Size: Can grow until memory limits
- *Efficiency: All operations work in constant time
- *Versatility: Foundation for many algorithms
Stack Implementation using Array
// Stack Implementation using Array (JavaScript)
class Stack {
constructor(size = 10) {
this.items = new Array(size);
this.top = -1;
this.capacity = size;
}
// Push operation
push(element) {
if (this.isFull()) {
console.log("Stack Overflow");
return;
}
this.items[++this.top] = element;
}
// Pop operation
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow");
return undefined;
}
return this.items[this.top--];
}
// Peek operation
peek() {
if (this.isEmpty()) {
console.log("Stack is empty");
return undefined;
}
return this.items[this.top];
}
// Check if stack is empty
isEmpty() {
return this.top === -1;
}
// Check if stack is full
isFull() {
return this.top === this.capacity - 1;
}
// Get stack size
size() {
return this.top + 1;
}
// Print stack contents
print() {
if (this.isEmpty()) {
console.log("Stack is empty");
return;
}
console.log("Stack contents:");
for (let i = this.top; i >= 0; i--) {
console.log(this.items[i]);
}
}
}
// Usage
const stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
console.log("Top element:", stack.peek()); // 30
console.log("Stack size:", stack.size()); // 3
stack.print();
stack.pop();
console.log("After pop, top element:", stack.peek()); // 20
Features: Push, Pop, Peek, isEmpty, isFull, Size, and Print operations
Note: All implementations use fixed-size arrays and handle stack overflow/underflow