-
Notifications
You must be signed in to change notification settings - Fork 0
/
liststack.py
executable file
·74 lines (64 loc) · 1.96 KB
/
liststack.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
62
63
64
65
66
67
68
69
70
71
72
73
74
from core.exceptions import Empty
class LinkedStack:
"""
LIFO Stack implementation using a singly linked list for storage.
"""
# nested _Node class
class _Node:
"""
Lightweight, nonpublic class for storing a singly linked node.
"""
# streamline memeory usage
__slots__ = '_element', '_next'
def __init__(self, element, next):
# reference to user's element
self._element = element
# reference to next node
self._next = next
# stack methods
def __init__(self):
"""
Create an empty stack.
"""
# reference to the head node
self._head = None
# number of the stack elements
self._size = 0
def __len__(self):
"""
Return the number of elements in the stack.
"""
return self._size
def is_empty(self):
"""
Return True if the stack is empty.
"""
return self._size == 0
def push(self, e):
"""
Add element e to the top of the stack.
"""
# create and link a new node
self._head = self._Node(e, self._head)
self._size += 1
def top(self):
"""
Return (but do not remove the element at the top of the stack.
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty('Stack is empty')
# top of stack is at head of list
return self._head._element
def pop(self):
"""
Remove and return the element from the top of the stack (i.e., LIFO).
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty('Stack is empty')
answer = self._head._element
# bypass the former top node
self._head = self._head._next
self._size -= 1
return answer