Reputation: 13
I want to create a linked list where each node's cargo has two pieces of data.
This is what I've got so far, it runs without errors, but produces no output.
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, data):
self.head = None
self.label = data[0][0]
self.value = data[0][1]
self.tail = None if (len(data) == 1) else LinkedList(data[1:])
def __iter__(self):
node = testlist.head
while node:
yield node
node = node.next
testlist = LinkedList()
print([node.value for node in testlist])
Upvotes: 1
Views: 237
Reputation: 71517
I see a few problems with your code:
Your __iter__
method doesn't iterate over self
, it iterates over testlist
(which isn't in itself a problem for your specific test case, but this is going to break in any other situation)
Your __init__
method does not actually construct a linked list. It simply initializes head
to None, which means that your __iter__
will never have anything to traverse.
Nothing uses your Node
class. In a typical linked list implementation, the head
of the list would be a Node
representing the first element of the list, the next
of that Node
would be the second element, etc.
Upvotes: 2