python-3.x - 我在尾部函数中的插入节点不会改变尾部的值
问题描述
所以我试图编写一个函数,它将链表的头部和数据作为参数,并在链表的尾部附加一个节点。当它从函数内部打印“新”头时,它看起来工作正常(请注意,链表的头最初不是节点,它实际上等于 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))
解决方案
以下是固定代码:
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)
由于头指针是通过赋值传递的,head
因此函数的local版本发生了InsertNode
变化,但原始版本llist.head
不受影响。
推荐阅读
- graphics - glsl“统一网格”分桶
- django-rest-framework - Wagtail 和 DRF 的难度
- php - 使用zend框架3在php中进行多处理
- ruby-on-rails - Ruby on Rails - 需要为应用程序使用旧版本的 ruby
- angular - 角度计数数组中的总项目而不减慢速度
- node.js - 是否可以覆盖节点模块路径?
- json - Ansible from_json 过滤不返回输出
- ios - 在自定义单元格的 tableView(_:cellForRowAt:) 中以编程方式添加标签
- java - 在 Java 8 中使用先前链接的 thenCompose lambdas 中的值
- php - 如何检查数组下一个索引是否存在于php中?