December 2023
Intermediate to advanced
504 pages
11h 43m
English
Most programming languages don’t come with the stack as a built-in data type or class. Instead, it’s up to you to implement it yourself. This is a stark contrast with arrays, which are available in most languages.
To create a stack, then, you generally have to use one of the built-in data structures to hold the data. Here’s one way to implement a stack using Python, which uses an array under the hood:
| | class Stack: |
| | def __init__(self): |
| | self.data = [] |
| | |
| | def push(self, element): |
| | self.data.append(element) |
| | |
| | def pop(self): |
| | if len(self.data) > 0: |
| | return self.data.pop() |
| | else: |
| | return None |
| | |
| | def read(self): |
| | if len(self.data) > 0: |
| | return self.data[-1] |
| | else: |
| | return None |
Read now
Unlock full access