Dimitris Kougioumtzis Blog About technology

Linked List

Category Python

Posted on April 7, 2018



Linked list


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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)

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere