0

I am writing a code for reversing a linked list in python. The following code does not pass the test case:

class ListNode(object):
    def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution(object):
    def reverseList(self, head)    
        prev, curr = None, head
        while curr:
            curr.next = prev
            prev = curr 
            curr = curr.next
        return prev

while this code passes:

class Solution(object):        
    def reverseList(self, head):  # Iterative
        prev, curr = None, head
        while curr:
            curr.next, prev, curr = prev, curr, curr.next
        return prev

What is the difference between the two?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Well, you can see which lines of code have been changed, right? So the question is really "why does that make a difference?", yes? – Karl Knechtel Mar 31 '21 at 03:47
  • Does https://stackoverflow.com/questions/16409901/simultaneous-assignment-semantics-in-python help you understand? – Karl Knechtel Mar 31 '21 at 03:49

1 Answers1

0

In your unrolled code, by the time you get to the last line, curr.next has been overwritten with prev. It no longer has its original value. Both prev and curr will point to the old prev.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30