I am reversing a singly- linked list with the following code:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return []
curr = head.next
prev = head
while curr:
curr.next = prev
curr = curr.next
prev = prev.next
return curr
I am getting a TIME OUT error- but I can’t seem to see the issue. When I run the loop on paper it seems to work fine, any ideas what is causing, what I assume is the loop to not terminate? Thanks
There are a few issues:
-
curr.next
has already been modified by the time you docurr = curr.next
. So instead of going forward in the list, you’re going backward (sincecurr.next
is actually equal toprev
by that time). -
head.next
is never modified, yet it should becomeNone
. You should actually start one step “earlier” in the list, makingcurr
equal tohead
andprev
should beNone
. -
return curr
is always going to returnNone
, as that is the condition by which thewhile
loop exits.
Here is a fix:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
curr = head
prev = None
while curr:
nxt = curr.next # Remember what the next node is before losing the reference
curr.next = prev # Rewire.
prev = curr # Move the two references one step forward
curr = nxt # ... using the saved reference
return prev # Return what was the tail node, but now is the new head
So we use a temporary variable nxt
here. You could also use tuple assignment… then you don’t need the explicit temporary variable:
while curr:
curr.next, prev, curr = prev, curr, curr.next