4

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, 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 there is something wrong with it. I know if the Linked list is empty I have to create one, problem starts when there's 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)

Anyone can tell me what did I do wrong please? Any help is much appreciated.

3
  • In the case where ptr is not None (i.e., in the case where the list is non-empty), find the last node in the list, then you can do last.next = Node(item, None) Commented Oct 16, 2017 at 22:36
  • 2
    Terminology nitpick: append is not a class, it is a function, a method of your LinkedList class. Commented Oct 16, 2017 at 22:43
  • 1
    @juanpa.arrivillaga Thanks I fixed it Commented Oct 16, 2017 at 22:52

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

@OmOWalker Pretty much that. If you get to a point where ptr is None, and assign ptr, that doesn't mean you are reassigning the tail's next attribute! I hope that clears things up for you.
Yeah, I'll keep practicing :D. Gave you a vote up, but it says something about me having small reputation.
I think you meant to write ptr.next = Node(item, None) as last line. No alternative for proper testing.

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.