A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It means that the element which is added last is the first one to be removed. Stacks have two primary operations: push (to insert an element onto the stack) and pop (to remove an element from the top of the stack).
Array Representation of Stack:
In the array representation of a stack, a fixed-size array is used to implement the stack. The array has a fixed capacity, and the stack grows or shrinks within this fixed-size array. Typically, a pointer (often called top
) is used to keep track of the top element of the stack.
Here’s how a stack can be represented using an array in Python:
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = [None] * capacity # Initialize array with None values
self.top = -1 # Initialize top pointer to -1 (empty stack)
def is_empty(self):
return self.top == –1
def is_full(self):
return self.top == self.capacity – 1
def push(self, item):
if self.is_full():
print(“Stack Overflow”)
return
self.top += 1
self.stack[self.top] = item
def pop(self):
if self.is_empty():
print(“Stack Underflow”)
return None
item = self.stack[self.top]
self.top -= 1
return item
def peek(self):
if self.is_empty():
print(“Stack is empty”)
return None
return self.stack[self.top]
# Example usage
stack = Stack(5)
stack.push(1)
stack.push(2)
stack.push(3)
print(“Top element:”, stack.peek()) # Output: 3
print(“Popped element:”, stack.pop()) # Output: 3
Implementation of Stack using Array:
In the implementation provided above:
- The
push
operation inserts an element onto the stack by incrementing the top pointer and assigning the item to the corresponding position in the array. - The
pop
operation removes the top element from the stack by returning the element at the top position and decrementing the top pointer. - The
peek
operation returns the top element of the stack without removing it. - The
is_empty
andis_full
methods check if the stack is empty or full, respectively.
This implementation demonstrates how a stack can be efficiently implemented using an array. However, it’s important to note that this implementation has a fixed capacity, and resizing the array when it becomes full can be costly. Dynamic array-based implementations can be used to overcome this limitation.