-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkedbag.py
60 lines (52 loc) · 1.89 KB
/
linkedbag.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
from node import Node
from abstractbag import AbstractBag
class LinkedBag(AbstractBag):
"""A link-based bag implementation."""
# Constructor
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the
content of sourceCollection, if it's present."""
self._items = None
AbstractBag.__init__(self, sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of self."""
cursor = self._items
while not cursor is None:
yield cursor.data
cursor = cursor.next
# Mutator methods
def clear(self):
"""Make self become empty."""
self._size = 0
self._items = Array(ArrayBag.DEFAULT_CAPACITY)
def add(self, item):
"""Add item to self."""
# Check array memory here and increase it if necessary
self._items = Node(item, self._items)
self._size += 1
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
# Check precondition and raise if necessary
if not item in self:
raise KeyError(str(item) + " not in bag")
# Search for the node containing the target item
# probe will point to the target node, and trailer
# will point to the one before it, if it exists
probe = self._items
trailer = None
for targetItem in self:
if targetItem == item:
break
trailer = probe
probe = probe.next
# Unhook the node to be deleted, either the first one or the
# one thereafter
if probe == self._items:
self._items = self._items.next
else:
trailer.next = probe.next
# Decrement logical size
self._size -= 1