Linked Lists Insert Methode (Noch nicht ausreichend getestet); warum wird 789 mehrfach ausgegeben (unrelated to this commit)
This commit is contained in:
@@ -11,6 +11,33 @@ class LinkedList:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.head: Node | None = None
|
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 >:)
|
# Definition der "append" Methode ich mag push und pop lieber >:)
|
||||||
def push(self, data: int):
|
def push(self, data: int):
|
||||||
if self.head is None:
|
if self.head is None:
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ list = LinkedList()
|
|||||||
list.push(123)
|
list.push(123)
|
||||||
list.push(456)
|
list.push(456)
|
||||||
list.push(789)
|
list.push(789)
|
||||||
|
# list.insert(00000, 1)
|
||||||
list.print()
|
list.print()
|
||||||
|
|
||||||
print(list.pop())
|
print(list.pop())
|
||||||
|
|||||||
Reference in New Issue
Block a user