Я пытаюсь добавить элементы в конец моего связанного списка и не вижу, что это происходит. Кажется, что он добавляет None в конец связанного списка. Я не уверен, почему это происходит, и я предполагаю, что это должно что-то сделать с неправильной настройкой моего.next. Я использую python для реализации связанного списка. Может кто-нибудь, пожалуйста, помогите мне с этим
Ниже мой класс Node
class Node:
def __init__(self):
self.data = None
self.next = None
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def get_next(self):
return self.next
def set_next(self, node):
self.next = node
И вот мой связанный класс списка со способами вставки
class SingleyLinkedList:
def __init__(self):
self.head = Node()
def insertAtHead(self, data):
currentNode = self.head
newNode = Node()
newNode.set_data(data)
if currentNode != None:
newNode.set_next(currentNode)
self.head = newNode
print("Inserted ", data, " at the head")
else:
self.head.set_next(newNode)
def insertAtEnd(self, data):
currentNode = self.head
new_node = Node()
new_node.set_data(data)
while currentNode.get_next() != None:
currentNode = currentNode.next
currentNode.set_next(new_node)
print("Inserted ", data, " at end")
def printNode(self):
print("\nPrinting the nodes")
currentNode = self.head
while currentNode.next != None:
print(currentNode.data, " --> ", end="")
currentNode = currentNode.next
print(" NULL \n")
s = SingleyLinkedList()
s.insertAtHead(5)
s.printNode()
s.insertAtHead(10)
s.printNode()
s.insertAtHead(1)
s.printNode()
s.insertAtEnd(20)
s.printNode()
Я получаю следующий результат,
Вставить 5 в голову
Печать узлов 5 → NULL
Вставить 10 в голову
Печать узлов 10 → 5 → NULL
Вставить 1 во главе
Печать узлов 1 → 10 → 5 → NULL
Вставить 20 в конец
Печать узлов 1 → 10 → 5 → Нет → NULL
Сначала вы начинаете init с Node()
который содержит значения None
которые являются неправильными, у вас должна быть пустая голова, поэтому вы видите None
в конце, потому что она распространяется до конца и, наконец, вы не печатаете последний Node()
потому что последний У узла нет next
Это условие не показывает Node
без следующего:
while currentNode.next != None:
print(currentNode.data, " --> ", end="")
currentNode = currentNode.next
Поэтому вам нужно распечатать еще один.
Ниже рабочего примера с небольшим упрощением:
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def get_next(self):
return self.next
def set_next(self, node):
self.next = node
class SingleyLinkedList:
def __init__(self):
self.head = None
def insertAtHead(self, data):
old_head = self.head
self.head = Node(data, old_head)
print("Inserted ", data, " at the head")
def insertAtEnd(self, data):
currentNode = self.head
while currentNode.get_next() != None:
currentNode = currentNode.next
currentNode.set_next(Node(data))
print("Inserted ", data, " at end")
def printNode(self):
print("\nPrinting the nodes")
currentNode = self.head
while currentNode.next != None:
print(currentNode.data, " --> ", end="")
currentNode = currentNode.next
print(currentNode.data, " --> ", end="")
print(" NULL \n")
s = SingleyLinkedList()
s.insertAtHead(5)
s.printNode()
s.insertAtHead(10)
s.printNode()
s.insertAtHead(1)
s.printNode()
s.insertAtEnd(20)
s.printNode()
Выход:
Inserted 5 at the head
Printing the nodes
5 --> NULL
Inserted 10 at the head
Printing the nodes
10 --> 5 --> NULL
Inserted 1 at the head
Printing the nodes
1 --> 10 --> 5 --> NULL
Inserted 20 at end
Printing the nodes
1 --> 10 --> 5 --> 20 --> NULL
Проблема в вашем коде:
self.head = Node()
т.е. когда вы создаете экземпляр класса SingleyLinkedList. Вы назначаете головку связанного объекта списка на такой узел, рядом с которым None
.
Следовательно, вы получаете None
в своем заявлении на Printing the nodes 1 --> 10 --> 5 --> None --> NULL
Ниже приведен правильный код:
class Node:
def __init__(self):
self.data = None
self.next = None
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def get_next(self):
return self.next
def set_next(self, node):
self.next = node
class SingleyLinkedList:
def __init__(self):
self.head = None
def insertAtHead(self, data):
newNode = Node()
newNode.set_data(data)
if self.head:
newNode.next = self.head
self.head = newNode
else:
self.head = newNode
print "Inserted ", data, " at the head"
def insertAtEnd(self, data):
currentNode = self.head
new_node = Node()
new_node.set_data(data)
while currentNode.get_next() != None:
currentNode = currentNode.next
currentNode.set_next(new_node)
print("Inserted ", data, " at end")
def printNode(self):
print("\nPrinting the nodes")
currentNode = self.head
while currentNode != None :
print currentNode.data,
print " --> ",
currentNode = currentNode.next
print
s = SingleyLinkedList()
s.insertAtHead(5)
s.printNode()
s.insertAtHead(10)
s.printNode()
s.insertAtHead(1)
s.printNode()
s.insertAtEnd(20)
s.printNode()
И выход:
Inserted 5 at the head
Printing the nodes
5 -->
Inserted 10 at the head
Printing the nodes
10 --> 5 -->
Inserted 1 at the head
Printing the nodes
1 --> 10 --> 5 -->
Inserted 20 at end
Printing the nodes
1 --> 10 --> 5 --> 20 -->
Ваш insertAtEnd
верен, но ваш printNode
неверен. Как бы то ни было, он всегда заменяет последний элемент связанного списка с помощью NULL
. Это нормально, когда вы добавляете элементы в начало списка, потому что он подавляет пустой head
узел, с которым вы инициализируете связанный список. Но когда вы вставляете элементы в конце списка, этот фиктивный узел теперь находится в середине списка и будет отображаться как None
при печати.
s = SingleyLinkedList()
s.insertAtEnd(1)
s.insertAtEnd(2)
s.insertAtEnd(3)
печать
Printing the nodes
None --> 1 --> 2 --> NULL
Решение: инициализируйте self.head = None
и соответствующим образом обработайте этот случай в ваших методах.
self.head = Node()
вinit
должен бытьself.head = None
?self.head=None()
для инициализации пустого узла сself.data=None
иself.next=None
. Таким образом, мне просто нужно присвоить значения данным и затем