Leetcode 21 Merge Two Sorted Lists

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.

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        p1, p2 = l1, l2
        dummy = ListNode(0)
        p = dummy
        while p1 and p2:
            if p1.val <= p2.val:
                p.next = p1
                p1 = p1.next
            else:
                p.next = p2
                p2 = p2.next
            p = p.next
        if p1:
            p.next = p1
        else:
            p.next = p2
        return dummy.next

 

posted @ 2016-04-07 11:35  lilixu  阅读(107)  评论(0编辑  收藏  举报