-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
61 lines (52 loc) · 1.41 KB
/
stack.py
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
from ..linked_node.node import Node
class Stack:
def __init__(self, it=()):
"""
Initialize new list with optional iterable.
"""
self.head = None
self._size = 0
for value in it:
self.push(value)
def __repr__(self):
"""
Return a formatted string representing Stack.
"""
if self.head:
return f"Stack({ self.head.value !r}, ...)"
return f"Stack()"
def __str__(self):
"""
Return a string representing Stack.
"""
if self.head:
return f"Stack head: { self.head.value }, size: { self._size }"
return f"Empty stack"
def __len__(self):
"""
Return the number of values currently in the stack.
"""
return self._size
def peek(self):
"""
Retrieve the most recent item on the stack.
"""
if not self.head:
raise IndexError("")
return self.head.value
def pop(self):
"""
Retrieve and remove the most recent item from the stack.
"""
if not self.head:
raise IndexError("")
node = self.head
self.head = self.head._next
self._size -= 1
return node.value
def push(self, value):
"""
Insert a value into the stack.
"""
self.head = Node(value, self.head)
self._size += 1