1

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])

1 Answer 1

2

I see a few problems with your code:

  1. 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)

  2. 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.

  3. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Still new to this, I've looked at my program's logic again and got everything working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.