简体   繁体   English

使用 Pythonic 变量交换迭代地反转链表

[英]Reversing a linked list iteratively with Pythonic variable swapping

I was just practicing some Linked List questions when I came across something I couldn't explain.当我遇到一些我无法解释的事情时,我只是在练习一些链接列表问题。 So I was wondering if anyone could help me out.所以我想知道是否有人可以帮助我。

If I have a Linked List with nodes implemented as follows如果我有一个链接列表,其节点实现如下

class Node:
    def __init__(self, val, next):
        self.val = val
        self.next = next

I tried reversing the Linked List initially like so and it came up with an AttributeError: 'NoneType' object has no attribute 'next'我最初尝试像这样反转链接列表,它提出了一个AttributeError: 'NoneType' object has no attribute 'next'

prev = None
curr = head
while curr:
    prev, curr, curr.next = curr, curr.next, prev

And then I modified it to and it worked but I can't seem to wrap my head around it.然后我将它修改为并且它有效,但我似乎无法围绕它。

prev = None
curr = head
while curr:
    curr.next, prev, curr = prev, curr, curr.next

I'm aware that Python evaluates the RHS as a tuple and then assigns the values on the LHS from left to right but I can't seem to understand why both code snippets wouldn't be the same if this is the case.我知道 Python 将 RHS 评估为一个元组,然后从左到右分配 LHS 上的值,但我似乎无法理解为什么两个代码片段在这种情况下不会相同。

You might want to visualize things the following way:您可能希望通过以下方式可视化事物:

Your first code is equivalent to:您的第一个代码相当于:

prev = None
curr = head
while curr:
    tmp = curr, curr.next, prev
    prev = tmp[0]
    curr = tmp[1]
    curr.next = tmp[2]

whereas your second code is equivalent to:而您的第二个代码相当于:

prev = None
curr = head
while curr:
    tmp = prev, curr, curr.next
    curr.next = tmp[0]
    prev = tmp[1]
    curr = tmp[2]

you see the difference is, that in one case you first change curr and then you assign to curr.next , whereas in the other case you first change curr.next and then reassign curr .您会看到不同之处在于,在一种情况下,您首先更改curr然后分配给curr.next ,而在另一种情况下,您首先更改curr.next然后重新分配curr

python executes nothing in parallel. python 不并行执行任何操作。

It has to chose an order which is left to right for the variables to be assigned to.它必须选择一个从左到右的顺序来分配变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM