-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
70 lines (56 loc) · 1.96 KB
/
Copy pathstack.py
File metadata and controls
70 lines (56 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# from data_structures.linked_list import LinkedList
from data_structures.linked_list import Node
from data_structures.invalid_operation_error import InvalidOperationError
class Stack:
"""
A simple implementation of a Stack using a linked list.
Attributes:
- top: Points to the top of the stack.
Methods:
- push(value): Adds an item to the top of the stack.
- pop(): Removes an item from the top of the stack.
- peek(): Returns the value of the item located at the top of the stack without removing it.
- is_empty(): Checks if the stack is empty.
"""
def __init__(self):
self.top = None
def push(self, value):
"""
Adds an item to the top of the stack.
Parameters:
- value: The value to be added to the stack.
"""
new_top = Node(value)
new_top.next = self.top
self.top = new_top
def pop(self):
"""
Removes an item from the top of the stack.
Returns:
- The value of the item removed from the top of the stack.
Raises:
- InvalidOperationError: If pop is called on an empty stack.
"""
if self.top is None:
raise InvalidOperationError("Method not allowed on an empty collection")
value = self.top.value
self.top = self.top.next
return value
def peek(self):
"""
Returns the value of the item located at the top of the stack without removing it.
Returns:
- The value of the item at the top of the stack.
Raises:
- InvalidOperationError: If peek is called on an empty stack.
"""
if self.top is None:
raise InvalidOperationError("Method not allowed on an empty collection")
return self.top.value
def is_empty(self):
"""
Checks if the stack is empty.
Returns:
- True if the stack is empty, False otherwise.
"""
return self.top is None