python - 为什么更改链表的复制版本会更改原始链表?
问题描述
def is_palindromic_linked_list(head):
if head is None or head.next is None:
return True
slow = head
fast = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
head_second_half = reverse(slow) #6, 4, 2 => 2, 4, 6
copy_head_second_half = head_second_half #<------HERE: copied linkedlist
while (head is not None and head_second_half is not None):
if head.value != head_second_half.value:
break
head = head.next
head_second_half = head_second_half.next
reverse(copy_head_second_half) #<---HERE: reversed the copied version of the linkedlist to set it back to how it was.
if head is None or head_second_half is None:
return True
return False
def reverse(head):
prev = None
while (head is not None):
next = head.next
head.next = prev
prev = head
head = next
return prev
这有什么意义?链表的工作方式是否与变量不同,因为更改复制版本会更改原始版本?
解决方案
当可变对象发挥作用时,问题就开始了。在您的案例中,您引用的是同一个对象,这意味着每个标签都指向同一个对象。关于这个话题有太多要说的了,但我建议从这里开始阅读一些东西
推荐阅读
- python - 从文件中为每个时间戳添加 15 分钟
- android - Webview 不加载 AdSense 广告
- angular - 您如何解决 d.ts 文件中的 angular typescript 错误?特别是 msal
- python-3.x - 机器人框架:将结果从一个关键字传递到另一个关键字
- ios - 缺少构建在结构中的 dSYM 文件。Gitlab 将构建上传到 Crashlytics
- dart - 我希望 IconButton 中的 onPressed 方法返回一个新的容器
- ios - 我只想访问 iOS 中的一个特定日历
- java - JFugue 笔记更改无法正常工作
- visual-c++ - 由于 exe 中缺少依赖项但存在于 dll 上,因此无法将 dll 从导入到我的 exe 进程
- python - 如何根据数组从(地理)熊猫数据框中选择多行或传播聚类算法结果的元数据?