Если вы хотите, чтобы ваш метод мог быть вызван для класса, а не для объекта, вы должны сделать это stati c:
@staticmethod
def merge(head1, head2):
# etc...
Вы также можете сделать свой код намного яснее (в том числе для себя), используя подсказки типа, когда вы смешиваете, что такое List
, и что Node
:
from typing import Any, Optional
class Node:
def __init__(self, data: Any):
self.data = data
self.next: Optional[Node] = None # might be Optional["Node"] since it inside it's own definition, I'm not sure check the mypy docs
class LinkedList:
def __init__(self, head: Optional[Node] = None):
self.head = head
def append(self, new_data: Any) -> None:
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
@staticmethod
def merge(list1: "LinkedList", list2: "LinkedList") -> "LinkedList":
if list1.head is None:
return list2
if list2.head is None:
return list1
if list1.head.data <= list2.head.data:
head = list1.head
list1 = LinkedList(list1.head.next)
else:
head = list2.head
list2 = LinkedList(list2.head.next)
temp = LinkedList(head)
temp.head.next = LinkedList.merge(list1, list2).head
return temp
протестируйте его с помощью:
inp = [8, 11, 20, 24, 50]
inp2 = [5, 9, 10, 30, 33, 40, 45]
l = LinkedList()
l2 = LinkedList()
for i in inp:
l.append(i)
for i in inp2:
l2.append(i)
rez = LinkedList.merge(l, l2)
temp = rez.head
print(temp.data)
while temp.next:
temp = temp.next
print(temp.data)