首页 > 解决方案 > 我在尾部函数中的插入节点不会改变尾部的值

问题描述

所以我试图编写一个函数,它将链表的头部和数据作为参数,并在链表的尾部附加一个节点。当它从函数内部打印“新”头时,它看起来工作正常(请注意,链表的头最初不是节点,它实际上等于 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.xlinked-listnodes

解决方案


以下是固定代码:

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不受影响。


推荐阅读