为了方便理解我把前提阐述一下,大致的意思是说要用迭代器写一个列表,每次迭代要从头开始这也是我遇到的问题,迭代部分我写完了,我就是不太知道怎么重头开始迭代
You are given an implementation of a linked list. A linked list is a datastructure consisting of multiple elements that each store a value and a reference to the next element.
Implement iterating over all values inside the list. In order to do that, you need to implement two classes:
A class LinkedListIterator.
It should encapsulate a pointer to the next element to be returned
You might want to initialise an appropriate attribute in it's init method
It should implement the next method that
returns the next element from the LinkedList should there be one
raises a StopIteration Exception otherwise
A class IterableLinkedList that inherits from LinkedList.
It should have a method iter that returns a new LinkedListIterator when called.
linked_lst = IterableLinkedList()
linked_lst.insert("a")
linked_lst.insert(2)
linked_lst.insert("c")
for n in linked_lst:
print(n)
iter_linked_lst = iter(linked_lst)
print("iter_linked_lst: " + next(iter_linked_lst))
other_iter_linked_lst = iter(linked_lst)
print("other_iter_linked_lst: " + next(other_iter_linked_lst))
print("other_iter_linked_lst: " + str(next(other_iter_linked_lst)))
print("iter_linked_lst: " + str(next(iter_linked_lst)))
print("iter_linked_lst: " + str(next(iter_linked_lst)))
a
2
c
iter_linked_lst: a
other_iter_linked_lst: a
other_iter_linked_lst: 2
iter_linked_lst: 2
iter_linked_lst: c
class ListElement:
def __init__(self, val):
self.value = val
self.next = None
class Linked_List:
def __init__(self):
self.head = None
def insert(self, val):
if self.head == None:
self.head = ListElement(val)
else:
elem = self.head
while elem.next != None:
elem = elem.next
elem.next = ListElement(val)
class LinkedListIterator:
# YOUR CODE HERE
def __init__(self,head):
self.head = head
def __next__(self):
if self.head.head==None:
raise StopIteration
else:
elem=self.head
valueinListEle=(elem.head).value
elem.head= (elem.head).next
return valueinListEle
class IterableLinkedList(Linked_List):
# YOUR CODE HERE
def __iter__(self):
return LinkedListIterator(self)
这是我的输出结果,只能迭代一次
a
2
c
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-7-ae203cbea3a8> in <module>
15
16 iter_linked_lst = iter(linked_lst)
---> 17 print("iter_linked_lst: " + next(iter_linked_lst))
18 other_iter_linked_lst = iter(linked_lst)
19 print("other_iter_linked_lst: " + next(other_iter_linked_lst))
<ipython-input-5-f697cc021da4> in __next__(self)
6
7 if self.head.head==None:
----> 8 raise StopIteration
9 else:
10 elem=self.head
StopIteration: