C02_list/list_composite_pattern.py

72 lines
1.8 KiB
Python
Raw Normal View History

2024-10-20 18:27:58 +02:00
from abc import ABC, abstractmethod
class ListeElement(ABC):
@abstractmethod
def length(self):
pass
class Element(ListeElement):
def __init__(self, data):
self.data = data
self.next = None
def length(self):
# Rekursive Methode zur Berechnung der Länge
return 1 + self.next.length()
class Abschluss(ListeElement):
def length(self):
# Ein Abschluss hat keine Länge
return 0
class Liste:
def __init__(self):
self.head = Abschluss() # Der Kopf der Liste ist ein Abschluss
def insert(self, value):
new_element = Element(value)
new_element.next = self.head
self.head = new_element
def remove_first(self):
if isinstance(self.head, Abschluss):
return # Liste ist leer
self.head = self.head.next
def length(self):
return self.head.length()
def show_list(self):
current = self.head
while not isinstance(current, Abschluss):
print(current.data)
current = current.next
def search(self, value):
current = self.head
while not isinstance(current, Abschluss):
if current.data == value:
return current
current = current.next
return None
def insert_before(self, value, comp_value):
new_element = Element(value)
if isinstance(self.head, Abschluss):
return # Liste ist leer
if self.head.data == comp_value:
new_element.next = self.head
self.head = new_element
return
current = self.head
while current.next is not None and current.next.data != comp_value:
current = current.next
if current.next is not None:
new_element.next = current.next
current.next = new_element