-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedStack.py
51 lines (42 loc) · 1.33 KB
/
linkedStack.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
class LinkedStack:
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._head = None
self._size = 0
def is_empty(self):
return self._size == 0
def __len__(self):
return self._size
def push(self, e):
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
if self.is_empty():
raise Empty('stack is empty')
return self._head._element
def pop(self):
if self.is_empty():
raise Empty('stack is empty')
poppedElem = self._head._element
self._head = self._head._next
self._size -= 1
return poppedElem
# helper class for empty stack errors
class Empty(Exception):
pass
if __name__ == '__main__':
print("...running tests")
ls = LinkedStack()
assert ls.is_empty() == True, "Stack should begin as empty"
ls.push(1)
assert ls.top() == 1, "Top (following .push(1)) should return 1"
ls.push(2)
assert ls.pop() == 2, "Popped element should be 2 (following .push(2))"
for i in range(4):
ls.push(i)
assert len(ls) == 5, "Length should be 5 after four pushes"
print("All tests passed!")