如何在python中合并两个排序的链表

时间:2014-03-20 05:00:42

标签: python list merge linked-list sorted

我尝试了很多算法来合并链接列表...

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])

任何人都可以给我代码通过这些测试用例吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

def merge_lists(x,y):
    comb = []
    comb += x + y
    comb.sort()
    return comb

答案 1 :(得分:0)

此操作只是执行&#34;合并&#34; Merge Sort的步骤,可以在O(l1+l2)时间内完成。

一般前提是同时迭代两个(已排序的)列表,但只使用最低的头值推进列表,同时在结果输出中使用高级值。当两个源列表都用尽时,操作就完成了。

这是一些pseudo-code(由维基百科提供),并且不应该为链表数据类型翻译太难。为链表实施时,可以创建新列表,也可以破坏性地修改其中一个列表。

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