Leetcode-21题:Merge Two Sorted Li

2016-09-24  本文已影响20人  八刀一闪

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

代码:

def mergeTwoLists(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    head = ListNode(None)
    p = head

    while l1!=None and l2!=None:
        p.next = l1
        if l1.val < l2.val:
            p = p.next
            l1 = l1.next
        else:
            p.next = l2
            p = p.next
            l2 = l2.next

    if l1 != None:
        p.next = l1
    if l2 != None:
        p.next = l2

    return head.next
上一篇 下一篇

猜你喜欢

热点阅读