原始问题。
因此,我重写了原问题中描述的问题的代码,但是有人已经回答了这个问题,而我的重写将使他们的答案无效,所以我刚刚发布了一个新的问题。
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发布于 2019-03-09 18:06:27
在我看来,这次重写的目的似乎是为了减轻更换头部的特殊待遇。和以前的解决方案一样,它也缺乏不同逻辑元素的分离。在本例中,tmp用于两个目的:遍历列表,并充当虚拟对象来检查是否替换了head。
这离明确的dummy节点仅一步之遥,可以在列表前面加上列表以消除对头部的特殊处理,我认为这种干净的分离更简单、更容易理解:
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.nexthttps://codereview.stackexchange.com/questions/215100
复制相似问题