1

I have just started learning about linked lists and I can't seem to add a new node using a function. Here is my code:

class Node:

    def __init__(self, data):
        self.data = data
        self.next = None

    def __repr__(self):
        return self.data

class LinkedList:

    def __init__(self, nodes=None):
        self.head = None
        if nodes is not None:
            node = Node(data=nodes.pop(0))
            self.head = node
            # print(self.head)
            for elem in nodes:
                # print(elem)
                node.next = Node(data=elem)
                node = node.next
                # print(node)

    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(node.data)
            node = node.next
        nodes.append("None")
        return " - > ".join(nodes)

    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

    def add_first(self, node):
        node.next = self.head
        self.head = node


llist = LinkedList(["c"])
llist.add_first("j")
print(llist)

When I run this, I get AttributeError: 'str' object has no attribute 'next'. Why does it not recognise the 'next' from the Node class?

2
  • 1
    Add node = Node(node) at the start of your add_first function. Commented Aug 14, 2020 at 3:50
  • Yup @HenryYik. Gotcha Commented Aug 14, 2020 at 4:12

1 Answer 1

1

You have a minor mistake in your add_first() function.

I think this will help you:

def add_first(self, s):
     node = Node(s)
     node.next = self.head
     self.head = node
Sign up to request clarification or add additional context in comments.

Comments

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.