, когда я пытаюсь отсортировать связанный список, используя сортировку слиянием, я получаю эту ошибку: AttributeError: 'NoneType' object has no attribute 'info'
методы вызова:
mList = SingleLinkedList()
mList.create_list()
mList.merge_sort()
сообщение об ошибке:
PS C:\Users\Slimane\Desktop\helloworld> & C:/Users/Slimane/AppData/Local/Programs/Python/Python38/python.exe c:/Users/Slimane/Desktop/helloworld/Untitled-1.py
Enter the number of the nodes: 5
Enter the data: 4
Enter the data: 3
Enter the data: 9
Enter the data: 1
Enter the data: 7
Traceback (most recent call last):
File "c:/Users/Slimane/Desktop/helloworld/Untitled-1.py", line 89, in <module>
mList.merge_sort()
File "c:/Users/Slimane/Desktop/helloworld/Untitled-1.py", line 73, in merge_sort
self.start = self._merge_sort_rec(self.start)
File "c:/Users/Slimane/Desktop/helloworld/Untitled-1.py", line 80, in _merge_sort_rec
start1 = self._merge_sort_rec(start1)
File "c:/Users/Slimane/Desktop/helloworld/Untitled-1.py", line 82, in _merge_sort_rec
startM = self._merge1(start1, start2)
File "c:/Users/Slimane/Desktop/helloworld/Untitled-1.py", line 39, in _merge1
if p1.info<= p2.info:
AttributeError: 'NoneType' object has no attribute 'info'
мой код :
class Node:
def __init__(self, value):
self.info = value
self.link = None
class SingleLinkedList:
def __init__(self):
self.start = None
def create_list(self):
n = int(input("Enter the number of the nodes: "))
for i in range(n):
data = int(input("Enter the data: "))
self.insert_at_end(data)
def display_list(self):
if self.start is None:
print("The list is empty!")
else:
print("the list contains: ")
p = self.start
while p is not None:
print(p.info, " ", end=" ")
p = p.link
print()
def insert_at_end(self, data):
temp = Node(data)
if self.start is None:
self.start = temp
else:
p = self.start
while p.link is not None:
p = p.link
p.link = temp
def _merge1(self, p1, p2):
if p1.info<= p2.info:
startM = Node(p1.info)
p1 = p1.link
else:
startM = Node(p2.info)
p2 = p2.link
pM = startM
while p1 != None and p2 != None:
if p1.info < p2.info:
pM.link = Node(p1.info)
p1 = p1.link
else:
pM.link = Node(p2.info)
p2 = p2.link
pM = pM.link
else:
while p1 != None:
pM.link = Node(p1.info)
p1 = p1.link
while p2 != None:
pM.link = Node(p2.info)
p2 = p2.link
return startM
def _divide_list(self, p):
q = p.link.link
while q is not None and q.link is not None:
p = p.link
q = q.link.link
start2 = p.link
p.link = None # this important line of code cut the list in the last node we reach
return start2
def merge_sort(self):
self.start = self._merge_sort_rec(self.start)
def _merge_sort_rec(self, listStart):
if listStart.link is None and listStart is not None:
return
start1 = listStart
start2 = self._divide_list(listStart)
start1 = self._merge_sort_rec(start1)
start2 = self._merge_sort_rec(start2)
startM = self._merge1(start1, start2)
return startM