我尝试了很多算法来合并链表…
def merge_lists(head1,head2):
if head1 is None and head2 is None:
return None
elif head1 is None:
return head2
elif head2 is None:
return head1
if head1.value <= head2.value:
result = head1
else:
result = head2
while head1 != None or head2 != None:
if head1 != None and head2 != None:
if head1.value <= head2.value:
result.next = head1
head1 = head1.next
else:
result.next = head2
head2 = head2.next
elif(head1!=None):
result.next = head1
elif(head2!=None):
result.next = head2
return result
pass
例如。,测试用例为
assert [] == merge_lists([],[])
assert [1,2,3] == merge_lists([1,2,3], [])
assert [1,2,3] == merge_lists([], [1,2,3])
assert [1,1,2,2,3,3,4,5] == merge_lists([1,2,3], [1,2,3,4,5])
assert [1,10] == merge_lists([10], [1])
assert [1,2,4,5,6,7] == merge_lists([1,2,5], [4,6,7])
谁能给我代码来通过这些测试用例?
这个操作只是做归并排序的"归并"步骤,可以在O(l1+l2)
时间内完成。
一般的前提是同时遍历两个(已经排序的)列表,但只推进头值最低的列表,同时在结果输出中使用高级值。当两个源列表都用完时,操作完成。
下面是一些伪代码(由维基百科提供),对于链表数据类型应该不会太难翻译。当在链表中实现它时,可以创建一个新的链表,也可以破坏性地修改其中一个链表。
function merge(left, right)
// receive the left and right sublist as arguments.
// 'result' variable for the merged result of two sublists.
var list result
// assign the element of the sublists to 'result' variable until there is no element to merge.
while length(left) > 0 or length(right) > 0
if length(left) > 0 and length(right) > 0
// compare the first two element, which is the small one, of each two sublists.
if first(left) <= first(right)
// the small element is copied to 'result' variable.
// delete the copied one(a first element) in the sublist.
append first(left) to result
left = rest(left)
else
// same operation as the above(in the right sublist).
append first(right) to result
right = rest(right)
else if length(left) > 0
// copy all of remaining elements from the sublist to 'result' variable,
// when there is no more element to compare with.
append first(left) to result
left = rest(left)
else if length(right) > 0
// same operation as the above(in the right sublist).
append first(right) to result
right = rest(right)
end while
// return the result of the merged sublists(or completed one, finally).
// the length of the left and right sublists will grow bigger and bigger, after the next call of this function.
return result
def merge_lists(x,y):
comb = []
comb += x + y
comb.sort()
return comb