算法链表合并

来源:互联网 发布:网络时时彩案件判刑 编辑:程序博客网 时间:2024/05/21 12:43

# iterativelydef mergeTwoLists1(self, l1, l2):    dummy = cur = ListNode(0)    while l1 and l2:        if l1.val < l2.val:            cur.next = l1            l1 = l1.next        else:            cur.next = l2            l2 = l2.next        cur = cur.next    cur.next = l1 or l2    return dummy.next    # recursively    def mergeTwoLists2(self, l1, l2):    if not l1 or not l2:        return l1 or l2    if l1.val < l2.val:        l1.next = self.mergeTwoLists(l1.next, l2)        return l1    else:        l2.next = self.mergeTwoLists(l1, l2.next)        return l2        # in-place, iteratively        def mergeTwoLists(self, l1, l2):    if None in (l1, l2):        return l1 or l2    dummy = cur = ListNode(0)    dummy.next = l1    while l1 and l2:        if l1.val < l2.val:            l1 = l1.next        else:            nxt = cur.next            cur.next = l2            tmp = l2.next            l2.next = nxt            l2 = tmp        cur = cur.next    cur.next = l1 or l2    return dummy.next

http://www.cnblogs.com/qieerbushejinshikelou/p/3917302.html

https://segmentfault.com/a/1190000003718892

https://leetcode.com/problemset/algorithms/

0 0
原创粉丝点击