我在尾部的插入节点功能不会改变尾部的值



因此,我试图编写一个函数,该函数将链表的头部和数据作为参数,并在链表的尾部添加一个节点。当它从函数内部打印"新"头时(头变成了head.data=0和head.next=None的节点(,它看起来工作得很好(注意,链表的头最初不是节点,实际上它等于None(,但当我在调用函数后打印链表的头时,它不会返回节点,事实上它返回None,这意味着函数没有在尾部插入节点,而尾部最初是头部。有人能解释为什么头部的价值没有改变吗?

class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def InsertNode(head, data):
if head == None:
print("head == None, so head will be a node now")
head = Node(data)
print("now, head is a node where head.data = {} and head.next = {}".format(head.data, head.next))
else: 
tail = head
while tail.next != None:
tail = tail.next
tail.next = Node(data)
def PrintLL(linkedList):
node = linkedList.head
while node != None:
print (node.data)
node = node.next
llist = LinkedList()
##print("llist.head == {}".format(llist.head))
InsertNode(llist.head, 0)
print("after InsertNode with data = 0, llist.head == {}".format(llist.head))

以下是固定代码:

class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def InsertNode(node, data):
if node.head == None:
print("head == None, so head will be a node now")
node.head = Node(data)
print("now, head is a node where head.data = {} and head.next = {}".format(node.head.data, node.head.next))
else: 
tail = node.head
while tail.next != None:
tail = tail.next
tail.next = Node(data)
def PrintLL(linkedList):
node = linkedList.head
while node != None:
print (node.data)
node = node.next
llist = LinkedList()
##print("llist.head == {}".format(llist.head))
InsertNode(llist, 0)
print("after InsertNode with data = 0, llist.head == {}".format(llist.head))

发生的事情是,你把一个指针传给了头部:

InsertNode(llist.head, 0)

然后InsertNode将为该变量分配一个新的节点实例:

head = Node(data)

由于头指针是通过赋值传递的,因此函数InsertNode本地的head版本发生了更改,但原始llist.head没有受到影响。

您需要将LinkedList对象本身传递给InsertNode,而不是其head属性。通过将head属性传递给InsertNode,对其进行的任何新分配都不会反映在原始对象上。

class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def InsertNode(linkedList, data):
if linkedList.head == None:
print("head == None, so head will be a node now")
linkedList.head = Node(data)
print("now, head is a node where head.data = {} and head.next = {}".format(linkedList.head.data, linkedList.head.next))
else:
tail = linkedList.head
while tail.next != None:
tail = tail.next
tail.next = Node(data)
def PrintLL(linkedList):
node = linkedList.head
while node != None:
print (node.data)
node = node.next
llist = LinkedList()
InsertNode(llist, 0)
print("after InsertNode with data = 0, llist.head == {}".format(llist.head.data))

最新更新