合并两个有序列表——递归&非递归

1、递归

def MergeTwo(l1, l2, tmp):
    if len(l1) == 0 or len(l2) == 0:
        tmp.extend(l1)
        tmp.extend(l2)
        return tmp
    else:
        if l1[0] < l2[0]:
            tmp.append(l1[0])
            del l1[0]
        else:
            tmp.append(l2[0])
            del l2[0]
        return MergeTwo(l1, l2, tmp)

def mergesort2(l1, l2):
    return MergeTwo(l1, l2, [])

print(MergeTwo(l1=[2, 4, 6, 8], l2=[1, 3, 5, 7, 9],temp = []))

2、非递归

def MergeTwo(l1, l2):
    tmp = []
    while len(l1) > 0 and len(l2) > 0:
        if l1[0] < l2[0]:
            tmp.append(l1[0])
            del l1[0]
        else:
            tmp.append(l2[0])
            del l2[0]
    tmp.extend(l1)
    tmp.extend(l2)
    return tmp

print(MergeTwo(l1=[2, 4, 6, 8], l2=[1, 3, 5, 7, 9]))

 

posted @ 2017-10-08 20:13  回冬  阅读(399)  评论(0编辑  收藏  举报