pythontimelinked-listreversereversing

Why is the time limit exceeding in reversing the linked list?


# Definition for singly-linked list.

 class ListNode:

     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev=ListNode(-1,head)
        curr=head
        dummy=head
        while dummy.next:
            curr.next=prev
            prev=dummy
            dummy=dummy.next
            curr=dummy
        return prev

I created three nodes, I used the prev and curr node for reversing and the dummy node for traversing ahead in the original linked list but I am getting time limit exceeded. I would like to know my logical error in this method


Solution

  • Some issues:

    Correction:

    class Solution:
        def reverseList(self, head):
            prev=None  # Don't create a new node
            curr=head
            while curr:  # Continue until the *last* node
                nxt=curr.next  # Save the next reference
                curr.next=prev
                prev=curr
                curr=nxt  # ... so you can move ahead
            return prev