Tutorialspoint
Problem
Solution
Submissions

Stack Using a List

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Create a Python class called Stack that implements a stack data structure using a list. The class should support standard stack operations such as push, pop, peek, is_empty, and size. The stack should follow the Last-In-First-Out (LIFO) principle.

Example 1
  • Input: stack = Stack()
  • Output: 30, 20
  • Explanation:
    • Step 1: Push elements like 10, 20, and 30 onto the stack.
    • Step 2: Pop the top element (30) and then peek the next top (20).
Example 2
  • Input: stack = Stack()
  • Output: False, 2
  • Explanation:
    • Step 1: Check if the stack is empty (False if it contains elements).
    • Step 2: Return the size of the stack (2 after two pushes).
Constraints
  • The stack can contain elements of any data type
  • Time Complexity: O(1) for all operations
  • Space Complexity: O(n) where n is the number of elements in the stack
  • Pop and peek operations on an empty stack should be handled gracefully
Functions / MethodsListAmazonMicrosoftGoogle
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Python's built-in list to store the stack elements
  • Define methods for each standard stack operation
  • For push, use list.append()
  • For pop, use list.pop() with no arguments
  • Implement error handling for operations on an empty stack
  • Consider implementing a max_size parameter (optional)

Steps to solve by this approach:

 Step 1: Create a Stack class with a list to store stack elements.

 Step 2: Implement push method to add items to the top of the stack.
 Step 3: Implement pop method to remove and return the top item.
 Step 4: Implement helper methods like peek, is_empty, and size.
 Step 5: Test the implementation with various stack operations.

Submitted Code :