首页 > 解决方案 > Python 变量引用(原始类型与对象)

问题描述

我一直在尝试练习一些链表 leet 代码问题。当我正在从链接列表中删除元素时,我很难理解“参考”。代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        current = head

        if head == None:
            return head
        
        if current != None:
            if current.val == val:
                head = current.next

        # print("current ", current)      
        while (current.next is not None):
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
         
        print("current",current)
        print("head", head)
        return head

首先是上面的代码没有通过所有的测试,但这不是我在这里遇到的问题。给定[1,2,6,3,4,5,6]输入链表的输入和要删除的节点是值为 的节点6,我注意到该print(head)语句导致正确的解决方案:

('head', ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}}})

但该print(current)语句只产生一个节点:

('current', ListNode{val: 5, next: None})

我明白为什么要current打印出单个节点,但是如何head打印出删除了 s 的正确链表6?据我所知,对于给定的输入,current被分配给head,所以如果我修改current只有它自己应该被修改而不是head正确的?显然我错了,但我的逻辑错误在哪里?

在 python 游乐场玩时,我确实注意到了一件事:

a = [1,2,3]
b = a
b.append(4)
# a = [1,2,3,4]
# b = [1,2,3,4]

c = 3
d = c
d = 4
# c = 3
# d = 4

我猜 python 对待原始类型的方式与其他对象不同?谢谢你。

标签: python-3.xreference

解决方案


推荐阅读