本文介绍了反向分配多个LinkedList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有以下代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head == None:
            return

        pre, node = None, head
        while node:
            pre, node.next, node = node, pre, node.next

        return pre

我正在试图对它的工作方式进行可视化处理.如果从列表开始,则 pre 成为 head ,因为 node 被分配给 head .然后将 node.next 分配给 pre ,那么它指向自身吗?最终, node 成为 node.next ,它本身就是?我在这里想念什么吗?

I am trying to vizualize how this works. If it starts on a list, the pre becomes the head, since node was assigned to head. then node.next is assigned to pre, so it points to itself? Finally, node becomes node.next, which is itself? am I missing something here?

推荐答案

多次分配与一次又一次的多次分配不同.区别在于,语句右侧的值在任何反弹之前都已评估.实际上,右侧的值打包在一个元组中,然后解压缩到左侧的名称中.

Multiple assignment isn't the same as several assignments one after the other. The difference is that the values on the right hand side of the statement all get evaluated before anything get rebound. The values on the right hand side are in fact packed up in a tuple, then unpacked into the names on the left hand side.

在这种情况下很重要,因为这意味着右侧的 node.next 会保存其值,以便在将其重新绑定到其他内容时( pre ),分配后旧值仍然可以成为新的 node 值.

That's important in this situation as it means that node.next on the right hand side gets its value saved, so that when you rebind it to something else (pre), the old value is still available to become the new node value after the assignment.

您可能想尝试一些更简单的任务,例如经典的交换操作:

You may want to play around with some simpler assignments, like the classic swap operation:

x = 1
y = 2

x, y = y, x  # swap x and y's values

print(x, y)  # prints "2 1"

_tup = y, x   # this is how it works, first pack the RHS values into a tuple
x, y = _tup   # then unpack the values into the names on the LHS

print(x, y)  # prints "1 2" as we've swapped back

这篇关于反向分配多个LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:16