Three concise python solution.


  • 7
    T

    Method 1: uses self as a dummy node for swapping

    def reverseList(self, head):
        pre, pre.next, tail = self, head, head
        while tail and tail.next:
            pre.next, pre.next.next, tail.next = \
                      tail.next, pre.next, tail.next.next
        return self.next
    

    Method 2: swapping using two variable, pre and cur

    def reverseList(self, head):
        pre, cur = None, head
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre
    

    Method 3: Recursive method by storing previous node in the function argument.

    def reverseList(self, head, pre = None):
        if not head: return pre
        cur, head.next = head.next, pre
        return self.reverseList(cur, head)

  • 0
    Z

    Amazing solution. Very concise. Thanks for sharing!


Log in to reply
 

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