python-3.x - 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 对待原始类型的方式与其他对象不同?谢谢你。
解决方案
推荐阅读
- java - 为什么 onCharacteristicRead 读取设置为 readCharacteristic 的不同特征
- flutter - 颤动的firebase身份验证提供者未通知
- spring-boot - 考虑在你的配置中定义一个 'org.springframework.transaction.jta.JtaTransactionManager' 类型的 bean
- javascript - 如何同时显示多个javascript数组
- javascript - 从路由中安全地检索值
- mongodb - MongoDB 3.2 到 3.6 升级性能/缓慢问题
- reactjs - 删除另一个文档后删除文档firebase firestore-react-web
- hadoop - impala 中的自定义健康检查
- r - filter_all 具有相对列位置(在任何列中过滤。然后在 n+2 列中)
- sql-server - SQL 性能:MSSQL 是否优化了日期时间函数的使用,还是将其作为参数传递更好