Reversing a LinkedList in with multiple assignment

风流意气都作罢 提交于 2021-01-28 08:02:16

问题


I have this code right down here:

# 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

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?


回答1:


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.

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



回答2:


The main idea is to convert the original head node becomes the last node of the new linked list and convert the original last one become the new head node and convert the link direction between nodes.

suppose the original linked list consists 2 nodes.

first, pre = None, the node = head, then node.next = pre that means the original head node becomes the last node of the new linked list. node = node.next that means to convert the link direction between nodes. node.next = pre means to convert the original last one becomes the new head.

while repeatedly execute the above process



来源:https://stackoverflow.com/questions/57017121/reversing-a-linkedlist-in-with-multiple-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!