diff options
| author | MatthiasMuth <99873492+MatthiasMuth@users.noreply.github.com> | 2023-05-21 21:59:46 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-05-21 21:59:46 +0200 |
| commit | dba8fa4ad8ac05cd7f92b1b8df63857d1d4b59c4 (patch) | |
| tree | deefa7edb1683505d41b95954b0dfc5b51a1a6e1 /challenge-071/lubos-kolouch/python/ch-2.py | |
| parent | f6448daebe7cffd67e484af066ebd21ad8e614b4 (diff) | |
| parent | 87c0bedd3ccc6c2459b62fc91429676507504d15 (diff) | |
| download | perlweeklychallenge-club-dba8fa4ad8ac05cd7f92b1b8df63857d1d4b59c4.tar.gz perlweeklychallenge-club-dba8fa4ad8ac05cd7f92b1b8df63857d1d4b59c4.tar.bz2 perlweeklychallenge-club-dba8fa4ad8ac05cd7f92b1b8df63857d1d4b59c4.zip | |
Merge branch 'manwar:master' into muthm-217
Diffstat (limited to 'challenge-071/lubos-kolouch/python/ch-2.py')
| -rw-r--r-- | challenge-071/lubos-kolouch/python/ch-2.py | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/challenge-071/lubos-kolouch/python/ch-2.py b/challenge-071/lubos-kolouch/python/ch-2.py new file mode 100644 index 0000000000..5662d38226 --- /dev/null +++ b/challenge-071/lubos-kolouch/python/ch-2.py @@ -0,0 +1,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) |
