This seems like a bug to me where I couldn't really figure it out why.
I have a very simple self-defined LinkedList class:
class MyLinkedList:
def __init__(self):
self.head = None
def __iter__(self):
self.currNode = self.head
return self
def __next__(self):
if self.currNode:
res = self.currNode
self.currNode = self.currNode.next
return res
else:
raise StopIteration
def addAtHead(self, val: int) -> None:
currNode = self.head
self.head = Node(val, currNode)
The problem comes inside iter method. After I added a node at head to a empty linkedList, the iter still think the self.head is None! In debug node, I can see self.head is a valid not none instance, but after assigning its value to self.currNode, self.currNode turns out to be None.
I thought it can be a problem of property issue so I changed the attribute to a property. But the problem still exists. Where am I wrong?
@property
def head(self):
return self._head
@head.setter
def head(self, x):
self._head = x
Adding my calling stack:
ll = MyLinkedList()
ll.addAtTail(6)
ll.addAtHead(5)
ll[0] # is None
#where a __getitem__ is defined as:
def __getitem__(self, i):
n = 0
for node in self:
if n == i:
return node
n += 1
raise IndexError
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next