C02_list/list.py

63 lines
1.6 KiB
Python
Raw Normal View History

2024-10-20 18:27:58 +02:00
class Element:
def __init__(self, data):
self.data = data
self.next = None
def length(self):
# Rekursive Methode zur Berechnung der Länge
if self.next is None:
return 1
else:
return 1 + self.next.length()
class Liste:
def __init__(self):
self.head = None
def insert(self, value):
new_element = Element(value)
new_element.next = self.head
self.head = new_element
def remove_first(self):
if self.head is not None:
self.head = self.head.next
def length(self):
if self.head is None:
return 0
else:
return self.head.length()
def show_list(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
def search(self, value):
current = self.head
while current is not None:
if current.data == value:
return current
current = current.next
return None
def insert_before(self, value, comp_value):
new_element = Element(value)
if self.head is None:
return
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