-
Notifications
You must be signed in to change notification settings - Fork 1
Stack
Pritam Kundu edited this page Aug 3, 2023
·
6 revisions
- A stack is a linear data-structure which follows LIFO principle
- Provides basic functionalities like push to insert items and pop to remove items.
- Also provides optional functionality like peek used to view item to be popped next.
- Implemented the stack using a python List as an Array in this module to demonstrate how stack implementation works with static arrays.
from datastax.Arrays import Stack
class Stack(AbstractStack):
def __init__(self, *, capacity: Optional[int] = sys.maxsize) -> None: ...
def is_full(self) -> bool: ...
def is_empty(self) -> bool: ...
def push(self, item: Any) -> int: ...
def pop(self) -> Any: ...
def peek(self) -> Any: ...
- Takes optional parameter capacity as a keyword Argument
- If not passed, the stack has maxsize capacity
Stack(10) # ❌ TypeError: Stack takes 1 positional argument but 2 were given
Stack(capacity=10) # ✅
- Takes no arguments.
- Returns True if stack is full.
Stack(capacity=0).is_full() # True
Stack(capacity=10).is_full() # False
- Takes no arguments.
- Returns True if stack is empty.
Stack(capacity=0).is_empty() # True
Stack(capacity=10).is_empty() # True
- Takes 1 argument of any type and inserts it in the end of the stack.
- Returns 0 on successful push operation.
- Raises
OverflowError
if stack is found full.
Stack().push(10) # 0 ✅
Stack(capacity=0).push(10) # ❌ OverflowError: Stack is already full, can't perform PUSH ...
- Takes no arguments and removes 1 item from the top of the stack.
- Returns the item of successful pop operation.
- Raises
UnderflowError
if stack is found empty.
s = Stack()
s.push(10)
s.pop() # 10 ✅
s.pop() # ❌ UnderflowError: Stack is already empty, can't perform POP ...
- Takes no arguments and returns the item from the top of the stack.
- returns
STACK EMPTY
if stack is found empty
s = Stack()
s.push(10)
s.peek() # 10
---
s.pop()
s.peek() # 'STACK EMPTY'
- 1. Home
- 2. Arrays
- 3. Nodes
- 4. Lists
- 5. Trees
- 6. Tables