Open links in new tab
  1. A stack is a linear data structure that follows the Last In First Out (LIFO) principle, where the last element added is the first one to be removed. Implementing a stack using an array involves using the end of the array to represent the top of the stack. This approach allows for efficient execution of stack operations such as push, pop, and peek.

    Implementation Steps

    1. Initialize an Array: Create an array to represent the stack and a variable to track the top of the stack.

    2. Push Operation: Add an element to the top of the stack. If the stack is full, handle the overflow condition.

    3. Pop Operation: Remove an element from the top of the stack. If the stack is empty, handle the underflow condition.

    4. Peek Operation: Return the top element of the stack without removing it.

    5. isEmpty Operation: Check if the stack is empty.

    6. isFull Operation: Check if the stack is full.

    Code Example

    Here is a Python implementation of a stack using an array:

    class Stack:
    def __init__(self, capacity):
    self.capacity = capacity
    self.stack = [None] * capacity
    self.top = -1

    def push(self, item):
    if self.isFull():
    print("Stack Overflow")
    return False
    self.top += 1
    self.stack[self.top] = item
    print(f"{item} pushed into stack")
    return True

    def pop(self):
    if self.isEmpty():
    print("Stack Underflow")
    return None
    item = self.stack[self.top]
    self.top -= 1
    return item

    def peek(self):
    if self.isEmpty():
    print("Stack is Empty")
    return None
    return self.stack[self.top]

    def isEmpty(self):
    return self.top == -1

    def isFull(self):
    return self.top == self.capacity - 1

    # Example usage
    stack = Stack(3)
    stack.push(10)
    stack.push(20)
    stack.push(30)
    print(stack.pop(), "Popped from stack")
    print("Top element is:", stack.peek())
    print("Elements present in stack:", end=" ")
    while not stack.isEmpty():
    print(stack.peek(), end=" ")
    stack.pop()
    Feedback
  1. Some results have been removed
Refresh