Skip to content Skip to sidebar Skip to footer

Python - Linked List - Append

I'm trying to learn Linked Lists in python I've been given Linked List class and asked to create append method. Here is the code provided. class Node: def __init__(self, item,

Solution 1:

Make two checks - the first checks whether self.head has been initialised. The second should traverse the list until it finds the last node. Ensure you don't overstep your boundaries, or else you won't be able to link the last node to the new last node.

def append(self, item):
    if not self.head:
        self.head = Node(item, self.head)
    else:
        ptr = self.head
        while ptr.next:                    # traverse until ptr.next is None
            ptr = ptr.next
        ptr.next = Node(item, ptr.next)    # initialise ptr.next

Post a Comment for "Python - Linked List - Append"