首页 > 解决方案 > Reverse singly linked list in python without using a temporary variable

问题描述

I am trying to solve some problems on Leetcode.

I completed the Reverse Linked List problem, which basically requires you to reverse a singly linked list. My solution is this:

def reverseList(self, head):
    curr = head
    prev = None
    if head != None:
        while (curr.next):
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        curr.next = prev
    return curr

I used a temp value to keep track of the original NEXT node after the current node, before the value of the NEXT node is changed in the following line.

However, when I compare my solution to other solutions, it seems that there was no need for a temporary value at all. Below is a sample solution:

def reverseList(self, head):
    curr, prev = head, None
    while curr:
        curr.next = prev
        prev = curr
        curr = curr.next
    return prev

No temporary value was used, which I am trying to figure out why. The below image is my mental visualisation of what happens in the solution:

enter image description here

Why is it possible for the code to be able to still assign curr = curr.next (line 4 of solution) after curr.next was mutated? (line 6 of solution)

标签: pythonlinked-list

解决方案


@lambert 说得对。

您在此处比较的特定解决方案不会逆转任何事情。将链表转换为新变量需要很长时间。


推荐阅读