Implementation
1"""
2Stack - LIFO Data Structure
3
4A stack is a linear data structure that follows the Last In,
5First Out (LIFO) principle. Elements are added and removed
6from the same end, called the "top" of the stack.
7
8Time Complexity:
9 - Push: O(1)
10 - Pop: O(1)
11 - Peek: O(1)
12 - Is Empty: O(1)
13
14Space Complexity: O(n) where n is number of elements
15"""
16
17
18class Stack:
19 def __init__(self):
20 """Initialize an empty stack."""
21 self.items = []
22
23 def push(self, item):
24 """Add an item to the top of the stack."""
25 self.items.append(item)
26
27 def pop(self):
28 """
29 Remove and return the top item from the stack.
30 Raises IndexError if stack is empty.
31 """
32 if self.is_empty():
33 raise IndexError("Cannot pop from empty stack")
34 return self.items.pop()
35
36 def peek(self):
37 """
38 Return the top item without removing it.
39 Raises IndexError if stack is empty.
40 """
41 if self.is_empty():
42 raise IndexError("Cannot peek empty stack")
43 return self.items[-1]
44
45 def is_empty(self):
46 """Return True if the stack is empty."""
47 return len(self.items) == 0
48
49 def size(self):
50 """Return the number of items in the stack."""
51 return len(self.items)
52
53 def __len__(self):
54 """Allow len(stack) syntax."""
55 return self.size()
56
57 def __str__(self):
58 """String representation: bottom -> top."""
59 return f"Stack({self.items})"
60
61
62# Example usage:
63if __name__ == "__main__":
64 stack = Stack()
65
66 # Push elements
67 stack.push(10)
68 stack.push(20)
69 stack.push(30)
70 print(stack) # Stack([10, 20, 30])
71
72 # Peek at top
73 print(stack.peek()) # 30
74
75 # Pop elements
76 print(stack.pop()) # 30
77 print(stack.pop()) # 20
78 print(stack) # Stack([10])
79