0

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)

2 Answers 2

1

You got it right, the second solution is just not working.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn I should have just tested it out myself to see if it was working, oh well.
1

@lambert has it right.

The particular solution you compare to here does not reverse anything. It takes a long way around shifting the linked list into a new variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.