Я создаю класс LinkedList, и я хочу определить метод удаления, который удалит узел из хвоста.Создание связанного класса списка и определение методов в python
До сих пор у меня есть:
class LinkedList:
def __init__(self):
self.head = None
def print_things(self):
current = self.head
while current != None:
print(current.get_data())
current = current.get_next()
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
def remove(self):
current = self.head
previous = None
found = False
while not found:
if current.get_data() != current:
found = True
else:
previous = current
current = current.get_next()
if previous == None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
return previous
Используя это, я пытаюсь запустить следующий код:
letter_list = LinkedList()
my_list.add('d')
letter_list.add('c')
letter_list.add('b')
letter_list.add('a')
print(letter_list.remove())
print(letter_list.remove())
print(letter_list.remove())
print('l')
letter_list.print_things()
который дает выход:
None
None
None
l
d
Даже если я ожидалось:
d
c
b
l
a
И это класс узел используется:
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
Я не могу видеть, что я сделал неправильно в моем методе удалить, но на основе вывода кажется я возвращаюсь в ту переменную.
Что такое 'if current.get_data()! = Current:' предполагается делать? При каких обстоятельствах результат 'get_data()' на узле равен узлу, и когда он не будет равен?Отображение вашего класса «Node» поможет получить ответ, поскольку указанный выше код зависит от его реализации. –