Python - Linked List - Add

I am trying to learn Linked Lists in python. I was given the Linked List class and asked to create an append method.

Here is the code.

class Node:
    def __init__(self, item, next):
        self.item = item
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, item):
        self.head = Node(item, self.head)

    def remove(self):
        if self.is_empty():
            return None
        else:
            item = self.head.item
            self.head = self.head.next
            return item

    def is_empty(self):
        return self.head == None

    def __str__(self):
        tmp_str = ""
        ptr = self.head
        while ptr != None:
            tmp_str += ptr.item + " "
            ptr = ptr.next

        return tmp_str

Here is my append method, but something is wrong with it. I know that if the linked list is empty, I have to create it, the problem starts when there are elements inside.

def append(self, item):
    ptr = self.head
    if ptr:
        while ptr != None:
            ptr = ptr.next
        ptr = Node(item, ptr)
    else:
        self.head = Node(item, self.head)

Can anyone tell me what I did wrong? Any help is greatly appreciated.

+4
source share
1 answer

Make two checks - the first checks to see if it has been initialized self.head. The second should cross the list until it finds the last node. Make sure that you don’t cross the borders, otherwise you cannot associate the last node with the 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
+3
source

Source: https://habr.com/ru/post/1687594/


All Articles