-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpractice8.py
70 lines (49 loc) · 2.09 KB
/
practice8.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
# Linked List Iterator
# In this practice, you will be overriding built-in magic methods to iterate over a linked list. You will see a very simple Node & LinkedList class in the REPL.
# Implement another class called LinkedListIterator that uses the magic methods __init__, __iter__, and __next__ to allow for iteration over an instance of the LinkedList class with a for loop:
# __init__ should initialize an instance property that keeps track of the current node.
# __iter__ must return an interator object, in other words an object that implements __next__.
# __next__ should return the value of the current node and then move the current node to the next node in the linked list. If the current node is None, raise the built-in StopIteration exception to stop iterating.
# We are iterating over the LinkedList class itself, so this class will also need a __iter__ method that returns an iterator object. Do not modify the Node class.
# Write your class here.
class LinkedListIterator:
def __init__(self, cur_node):
self.cur_node = cur_node
def __iter__(self):
return self
def __next__(self):
if self.cur_node is None:
raise StopIteration
cur_node_val = self.cur_node._value
self.cur_node = self.cur_node._next
return cur_node_val
class Node:
def __init__(self, value):
self._value = value
self._next = None
class LinkedList:
def __init__(self):
self._head = None
self._tail = None
self._length = 0
def add(self, value):
new_node = Node(value)
if self._head is None:
self._head = new_node
else:
self._tail._next = new_node
self._tail = new_node
self._length += 1
return self
def __iter__(self):
return LinkedListIterator(self._head)
linked_list = LinkedList()
linked_list.add('node 1')
linked_list.add('node 2')
linked_list.add('node 3')
linked_list.add('node 4')
linked_list.add('node 5')
# this loop should print "Current node: node x" five times
# for each node in the linked list
for i in linked_list:
print(f"Current node: {i}")