首页 > 解决方案 > 为什么更改链表的复制版本会更改原始链表?

问题描述

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

这有什么意义?链表的工作方式是否与变量不同,因为更改复制版本会更改原始版本?

标签: pythonpython-3.xlinked-listpalindrome

解决方案


可变对象发挥作用时,问题就开始了。在您的案例中,您引用的是同一个对象,这意味着每个标签都指向同一个对象。关于这个话题有太多要说的了,但我建议从这里开始阅读一些东西


推荐阅读