Stack Implementation using Array.
An array provides a contiguous memory block to store stack elements, allowing direct access to elements via their indices. A top pointer or index is used to keep track of the top element of the stack within the array.
Implementation of stack operations like push, pop, and peek is easy in array as we have direct access to elements using indices, providing constant-time access O(1). However, arrays have a fixed size, limiting the maximum capacity of the stack.
Let's understand how to implement each stack operation using an array:
First of all, we have to define an array to store stack elements and initialize an index variable (top) to keep track of the top element.
Implement Push Operation:
- Create a push function that takes a value as input.
- Check if the stack is full (array size is reached), and handle overflow if needed.
- Increment the top pointer and insert the value at the incremented index.
Implement Pop Operation:
- Create a pop function.
- Check if the stack is empty (top is -1), and handle underflow if needed.
- Retrieve the value at the top index, decrement the top pointer, and return the value.
Implement Peek Operation:
- Create a peek function.
- Check if the stack is empty.
- Return the value at the top index without modifying the stack.
Implement isEmpty Operation:
- Create an isEmpty function.
- Check if the top pointer is -1 (indicating an empty stack).
- Return True if the stack is empty; otherwise, return False.
Stack Implementation Code.
Below is the code implementation of the stack using an array in C++, Java, Python, and C# language.
// C++ program to implement stack using array #include <iostream> using namespace std; class Stack { private: static const int MAX_SIZE = 1000; // Maximum size of the stack int arr[MAX_SIZE]; int top; public: Stack() : top(-1) {} // Push operation void push(int value) { if (top >= MAX_SIZE - 1) { cout << "Stack Overflow. Cannot push." << endl; return; } arr[++top] = value; } // Pop operation void pop() { if (isEmpty()) { cout << "Stack is empty. Cannot pop." << endl; return; } top--; } // Check if the stack is empty bool isEmpty() { return top == -1; } // Display the top element of the stack void peek() { if (isEmpty()) { cout << "Stack is empty." << endl; return; } cout << "Top element: " << arr[top] << endl; } }; int main() { // Example usage of the stack Stack stack; // Push elements onto the stack stack.push(1); stack.push(2); stack.push(3); // Display the top element stack.peek(); // Pop an element stack.pop(); // Display the top element after pop stack.peek(); return 0; }
// Java program to implement stack using Array public class Main { private static final int MAX_SIZE = 1000; // Maximum size of the stack static class Stack { private int[] arr; private int top; Stack() { arr = new int[MAX_SIZE]; top = -1; } // Push operation void push(int value) { if (top >= MAX_SIZE - 1) { System.out.println("Stack Overflow. Cannot push."); return; } arr[++top] = value; } // Pop operation void pop() { if (isEmpty()) { System.out.println("Stack is empty. Cannot pop."); return; } top--; } // Check if the stack is empty boolean isEmpty() { return top == -1; } // Display the top element of the stack void peek() { if (isEmpty()) { System.out.println("Stack is empty."); return; } System.out.println("Top element: " + arr[top]); } } public static void main(String[] args) { // Example usage of the stack Stack stack = new Stack(); // Push elements onto the stack stack.push(1); stack.push(2); stack.push(3); // Display the top element stack.peek(); // Pop an element stack.pop(); // Display the top element after pop stack.peek(); } }
# Python code to implement stack using array class Stack: MAX_SIZE = 1000 # Maximum size of the stack def __init__(self): self.arr = [0] * self.MAX_SIZE self.top = -1 # Push operation def push(self, value): if self.top >= self.MAX_SIZE - 1: print("Stack Overflow. Cannot push.") return self.top += 1 self.arr[self.top] = value # Pop operation def pop(self): if self.is_empty(): print("Stack is empty. Cannot pop.") return self.top -= 1 # Check if the stack is empty def is_empty(self): return self.top == -1 # Display the top element of the stack def peek(self): if self.is_empty(): print("Stack is empty.") return print("Top element:", self.arr[self.top]) # Example usage of the stack stack = Stack() # Push elements onto the stack stack.push(1) stack.push(2) stack.push(3) # Display the top element stack.peek() # Pop an element stack.pop() # Display the top element after pop stack.peek()
// C-Sharp Code to implement stack using array using System; public class StackArray { private const int MAX_SIZE = 1000; // Maximum size of the stack class Stack { private int[] arr; private int top; public Stack() { arr = new int[MAX_SIZE]; top = -1; } // Push operation public void Push(int value) { if (top >= MAX_SIZE - 1) { Console.WriteLine("Stack Overflow. Cannot push."); return; } arr[++top] = value; } // Pop operation public void Pop() { if (IsEmpty()) { Console.WriteLine("Stack is empty. Cannot pop."); return; } top--; } // Check if the stack is empty public bool IsEmpty() { return top == -1; } // Display the top element of the stack public void Peek() { if (IsEmpty()) { Console.WriteLine("Stack is empty."); return; } Console.WriteLine("Top element: " + arr[top]); } } static void Main() { // Example usage of the stack Stack stack = new Stack(); // Push elements onto the stack stack.Push(1); stack.Push(2); stack.Push(3); // Display the top element stack.Peek(); // Pop an element stack.Pop(); // Display the top element after pop stack.Peek(); } }
Top element: 3
Top element: 2
Advantages of Array-based Stack.
- Implementing a stack using an array is straightforward and requires minimum code compared to linked list implementations.
- Array-based stacks offer efficient access to elements using indices, providing constant-time access O(1).
- Array uses contiguous memory, consuming less memory overhead compared to linked lists which require additional pointers for each node.
Disadvantages of Array-based Stack.
- Arrays have a fixed size, limiting the maximum capacity of the stack. This constraint requires predefined sizing or dynamic resizing logic to handle overflow conditions.
- Dynamic resizing to accommodate more elements involves creating a new array with increased capacity and copying existing elements, resulting in time complexity O(n) for resizing operations.
- If the array's size is significantly larger than the current number of stack elements, it can lead to memory wastage.
Related Post:
No comments:
Post a Comment