Skip to main content
deleted 20 characters in body
Source Link
alecxe
  • 17.3k
  • 8
  • 51
  • 93

Thanks in advance.

Thanks in advance.

Source Link

Recommended improvements on beginner Linked List

I know this implementation is very bare-bones, but are there any improvements I can make to it? (E.g. more pythonic, style, speed, comments).

I was considering using @property decorators a bit more, but I thought that was overkill for this example.

Thanks in advance.

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

    def __str__(self):
        return "Node Object : val {}".format(self.value)

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

    @property
    def length(self):
        if self.head is None:
            return 0
        length = 1
        current = self.head
        while current.next is not None:
            current = current.next
            length += 1
        return length

    def append(self, node):
        if self.head is None:
            self.head = node
            return
        current = self.head
        while current.next is not None:
            current = current.next
        current.next = node

    def prepend(self, node):
        if self.head is None:
            self.head = node
            return
        node.next = self.head
        self.head = node

    def get(self, index):
        current = self.head
        for i in range(0, index):
            if current.next is not None:
                current = current.next
            else:
                return None
        return current

    def delete(self, val):
        if self.head.value is val:
            self.head = None
            return
        current = self.head
        while current.next is not None:
            if current.next.value is val:
                current.next = current.next.next
                return
            current = current.next