aboutsummaryrefslogtreecommitdiff
path: root/challenge-071/lubos-kolouch/python/ch-2.py
blob: 5662d382269d3983bef3b4df913c208adc5a7aaa (plain)
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
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None


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

    def append(self, data):
        if not self.head:
            self.head = Node(data)
        else:
            cur = self.head
            while cur.next:
                cur = cur.next
            cur.next = Node(data)

    def remove_from_end(self, n):
        if self.head is None:
            return
        size = 0
        cur = self.head
        while cur:
            size += 1
            cur = cur.next
        if n >= size:
            self.head = self.head.next if self.head.next else None
        else:
            cur = self.head
            for _ in range(size - n - 1):
                cur = cur.next
            cur.next = cur.next.next if cur.next and cur.next.next else None

    def __str__(self):
        values = []
        cur = self.head
        while cur:
            values.append(str(cur.data))
            cur = cur.next
        return ' -> '.join(values)


# Tests
ll = LinkedList()
for i in range(1, 6):
    ll.append(i)

for i in range(1, 7):
    ll.remove_from_end(i)
    print(ll)