I am writing a code for reversing a linked list in python. The following code does not pass the test case:
JavaScript
x
13
13
1
class ListNode(object):
2
def __init__(self, val=0, next=None):
3
self.val = val
4
self.next = next
5
class Solution(object):
6
def reverseList(self, head)
7
prev, curr = None, head
8
while curr:
9
curr.next = prev
10
prev = curr
11
curr = curr.next
12
return prev
13
while this code passes:
JavaScript
1
7
1
class Solution(object):
2
def reverseList(self, head): # Iterative
3
prev, curr = None, head
4
while curr:
5
curr.next, prev, curr = prev, curr, curr.next
6
return prev
7
What is the difference between the two?
Advertisement
Answer
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
.