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
asked Mar 9, 2019 at 16:24
\$\endgroup\$

1 Answer 1

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
answered Mar 9, 2019 at 18:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.