Reverse a linked list

  • + 0 comments

    Things that I like about this: 'while llist' is quite a nice and expressive way of continuing until you hit the terminal None. Returning 'previous_node', defaulted to None, handles the case of an empty llist (single value: None) 'correctly' for the definition.

    Things I'm not convinced about: Python should let you swap three variables inline without needing a temporary variable (a, b, c = c, a, b) but expressing things like this feels harder to read (and order is important) versus having a temporary variable and doing things on separate lines.

    def reverse(llist):    
        previous_node = None
        while (llist):
            # store next (forward) node link in a temporary name
            next_node = llist.next
            # update node and re-point 'next' backwards
            llist.next = previous_node
            # update the previous node pointer for the next loop
            previous_node = llist
            # advance the 'head' pointer to continue
            llist = next_node
        return previous_node