https://www.codewars.com/kata/linked-lists-sorted-insert/train/python
Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.
sortedInsert(1 -> 2 -> 3 -> null, 4) === 1 -> 2 -> 3 -> 4 -> null) sortedInsert(1 -> 7 -> 8 -> null, 5) === 1 -> 5 -> 7 -> 8 -> null) sortedInsert(3 -> 5 -> 9 -> null, 7) === 3 -> 5 -> 7 -> 9 -> null)
在排好序的链表中插入一个新元素。
我的算法:
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def sorted_insert(head, data):
h = head
new_node = Node(data)
if not head:
return new_node
while h.next:
if h.next.data>data:
break
h = h.next
new_node.next = h.next
h.next = new_node
if h.data>data:
h.data,new_node.data = new_node.data,h.data
return head
找到大于它的第一个节点Q,然后插入到Q前面,如果Q之前的节点 P的值比新节点data的值要大,那就将P的值和新节点的值交换
大神的算法
class Node(object):
def __init__(self, data, nxt = None):
self.data = data
self.next = nxt
def sorted_insert(head, data):
if not head or data < head.data: return Node(data, head)
else:
head.next = sorted_insert(head.next, data)
return head
用了递归调用。