Linked List

Python -- Posted on April 7, 2018

Linked list

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

    def __str__(self):
        return str(self.data)

    def get_data(self):
        return self.data


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

    def prepend_node(self, data):
        node = Node(data=data)
        if not self.head:
            self.head = node
        else:
            current = self.head
            self.head = node
            self.head.next = current
        self.counter += 1

    def append_node(self, data):
        node = Node(data=data)
        if not self.head:
            self.head = node
        else:
            self.head.next = node
        self.counter += 1

    def remove_node(self, data):
        current = self.head
        while current:
            if current.data == data:
                if not current.next:
                    self.head.next = None
                else:
                    self.head = current.next
                self.counter -= 1
                return True
            current = current.next
        print('data not found')
        return False

    def traverse(self):
        current = self.head
        while current:
            yield current
            current = current.next


if __name__ == '__main__':
    linked = LinkedList()
    linked.append_node(1)
    linked.append_node(2)
    linked.prepend_node(5)
    linked.remove_node(5)
    for node in linked.traverse():
        if node:
            print(node.data)
                  
   
            

Related Posts