python solution, keep the original head


  • 1
    E
        def reverseList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            ph = head  # a copy of head, so the head will be kept
            prev = None
            curr = ph
            while ph:
                ph = ph.next
                curr.next = prev
                prev = curr
                curr = ph
            return prev
    

    example linked list: A->B->C->null

    the trick is to create a reference point to null at first

    think of the nodes as: null A B C null

    then reverse or redo the reference when iterating the list: A->null then B->A then C->B


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.