为什么在Python中遍历链表时原始链表头会改变?我是不是做错了什么?

问题描述 投票:0回答:1

在下面的代码中,我没有改变Head的值,为什么我无法保留Head的值?输入是一个LinkedList:[5, 4, 2, 1]

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        superhead = head
        print("Head starting:", head)
        curr2, prev2 = head, None
        print("curr2:", curr2)
        print("Superhead:", superhead)
        print("Head before while loop:", head)
        count = max = 0
        while curr2:
            print("\nInside while: Head", head)
            temp2 = curr2.next
            curr2.next = prev2
            prev2 = curr2
            curr2 = temp2
        print("\nHead end:", head)

    Head starting: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
    curr2: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
    Superhead: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
    Head before while loop: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}

    Inside while: Head ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
    Inside while: Head ListNode{val: 5, next: None}
    Inside while: Head ListNode{val: 5, next: None}
    Inside while: Head ListNode{val: 5, next: None}

    Head end: ListNode{val: 5, next: None}

我尝试在 while 循环中打印 Head 的值,并看到它在那里发生变化。

python-3.x pointers data-structures while-loop linked-list
1个回答
0
投票

你的循环反转了链表。这意味着 头的节点将成为尾部。

这是您的示例的可视化。事情是这样开始的

   head  
     ↓ 
     5 → 4 → 3 → 2 → 1 → None
     ↑
   curr2
   

第一次迭代后,我们有:

     head  
       ↓ 
None ← 5   4 → 3 → 2 → 1 → None
           ↑
         curr2

第二次迭代后:

     head  
       ↓ 
None ← 5 ← 4   3 → 2 → 1 → None
               ↑
             curr2

如此一直持续到

curr2
None
:

     head  
       ↓ 
None ← 5 ← 4 ← 3 ← 2 ← 1   None
                            ↑
                          curr2

因此,如果您现在查看

head
并遵循
next
属性,您将立即到达
None
。其他节点无法通过
head
到达。如果你想打印从 1 开始的所有节点,那么你应该从
prev2
开始打印,循环后将引用值为 1 的节点。

© www.soinside.com 2019 - 2024. All rights reserved.