1
\$\begingroup\$

Original Question.

So I rewrote the code for the problem described in the original question, but someone had already answered that question, and my rewrite would have invalidated their answer, so I just posted a new question.

Updated Solution

def sorted_insert(head, data):
    tmp = Node(None)
    tmp.next = head
    node = Node(data)
    while tmp.next:
        if tmp.next.data > data:
            break
        tmp = tmp.next
    node.next = tmp.next
    tmp.next = node
    return head if tmp.data else node
\$\endgroup\$
2
\$\begingroup\$

To me it seems the purpose of this rewrite is to mitigate the special treatment for replacing the head. Like the previous solution, it also suffers from lack of separation of distinct logical elements. In this example, tmp is used for two purposes: traverse the list, and act as the dummy to check if head was replaced.

This is one step away from a clear dummy node to prefix the list to eliminate the special treatment of the head, and I think this clean separation is simpler and easier to understand:

def sorted_insert(head, data):
    # a dummy node inserted in front of head
    dummy = Node(None)
    dummy.next = head

    # whatever happens in the rest, the new head will be dummy.next

    # loop until the insertion point
    node = dummy
    while node.next:
        if node.next.data > data:
            break
        node = node.next

    # create the new node and insert it
    new_node = Node(data)
    new_node.next = node.next
    node.next = new_node

    # return the head. it may or may not have been replaced
    return dummy.next
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.