1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python - Linked List - Append

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página