Files
orientada-a-objectos/linked-lists/linked_list.py
T

95 lines
2.0 KiB
Python

from typing import Self
class Node:
def __init__(self, data: int):
self.data: int = data
self.next: Self | None = None
class LinkedList:
def __init__(self):
self.head: Node | None = None
def insert(self, data: int, insert_index: int):
if self.head is None:
self.head = Node(data)
return
node = self.head
assert node is not None
i = 1
while True:
ben = Node(37)
if node.next is None:
node.next = Node(data)
return
if i == insert_index or node.next == ben:
new_node = Node(data)
new_node.next = node.next
node.next = new_node
return
node = node.next
i += 1
print(i, insert_index)
assert i <= insert_index
# Definition der "append" Methode ich mag push und pop lieber >:)
def push(self, data: int):
if self.head is None:
self.head = Node(data)
return
node = self.head
assert node is not None
while True:
if node.next is None:
node.next = Node(data)
return
node = node.next
def pop(self) -> int | None:
if self.head is None:
return None
node = self.head
assert node is not None
if node.next is None:
data = node.data
self.head = None
return data
assert node.next is not None
while True:
prev_node = node
node = node.next
if node.next is None:
data = node.data
prev_node.next = None
return data
def len(self) -> int:
node = self.head
i = 0
while node is not None:
node = node.next
i += 1
return i
def print(self):
node = self.head
while node is not None:
print(node.data)
node = node.next