Snippets

Rodrigo Baron List implementation

Created by Rodrigo Baron
"""
Linked List implementation
"""
class Node(object):
    """Node class"""
    def __init__(self, value):
        self.value = value
        self.next = None

    def __repr__(self):
        return str(self.value)


class List(object):
    """List class"""
    def __init__(self):
        self.root = None
        self.count = 0

    def insert_start(self, value):
        """Inster value at beggining of list"""
        if not self.root:
            self.root = Node(value)
        else:
            node = Node(value)
            node.next = self.root
            self.root = node
        self.count = self.count + 1

    def insert_end(self, value):
        """Inster value at end of list"""
        if not self.root:
            self.root = Node(value)
        else:
            aux = self.root
            while aux.next:
                aux = aux.next
            aux.next = Node(value)
        self.count = self.count + 1

    def remove(self, value):
        """Remove all itens that match the value"""
        if not self.root:
            raise Exception('The list is empty')
        if self.root.value == value:
            matched = self.root
            self.root = self.root.next
            del matched
            self.count = self.count - 1
        else:
            aux = self.root
            while aux.next:
                if aux.next.value == value:
                    matched = aux.next
                    aux.next = aux.next.next
                    del matched
                    self.count = self.count - 1
                aux = aux.next

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.