【发布时间】:2018-12-18 22:22:02
【问题描述】:
所以我试图编写一个函数,它将链表的头部和数据作为参数,并在链表的尾部附加一个节点。当它从函数内部打印“新”头时,它看起来工作正常(请注意,链表的头最初不是节点,它实际上等于 None)(head 成为 head.data = 0 and head.next = 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))
【问题讨论】:
标签: python-3.x linked-list nodes