Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
73 views
in Information Technology by (178k points)
Can you provide an example code illustrating the limitations of a stack?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

Here is the code.

class Stack:
    def __init__(self, capacity):
        self.capacity = capacity
        self.stack = []

    def push(self, item):
        if len(self.stack) < self.capacity:
            self.stack.append(item)
        else:
            print("Stack overflow error")

    def pop(self):
        if self.stack:
            return self.stack.pop()
        else:
            print("Stack underflow error")
            return None

    def peek(self):
        if self.stack:
            return self.stack[-1]
        else:
            print("Stack is empty")
            return None

# Example usage:
stack = Stack(3)  # Create a stack with capacity 3
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)  # This will cause a stack overflow error
print(stack.peek())  # Output: 3
print(stack.pop())   # Output: 3
print(stack.pop())   # Output: 2
print(stack.pop())   # Output: 1
print(stack.pop())   # This will cause a stack underflow error
 

This example demonstrates how a stack's fixed size can lead to overflow and underflow errors, and its LIFO nature affects operations like pop and peek.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...