LintCode Python 简单级题目 165.合并两个排序链表

原题描述:

将两个排序链表合并为一个新的排序链表

样例

给出 1->3->8->11->15->null2->null, 返回 1->2->3->8->11->15->null

题目分析:

依次从l1,l2表头获取节点,将小的添加到l3

源码:

class Solution:
    """
    @param two ListNodes
    @return a ListNode
    """
    def mergeTwoLists(self, l1, l2):
        # write your code here
        if l1 is None: return l2
        if l2 is None: return l1
        new = ListNode(0)
        p1 = l1
        p2 = l2
        p3 = new
        while p1 is not None and p2 is not None:
            if p1.val < p2.val:
                p3.next = p1
                p1 = p1.next
            else:
                p3.next = p2
                p2 = p2.next
            p3 = p3.next
        else:
            if p1 is None:
                p3.next = p2
            else:
                p3.next = p1
        return new.next

  

posted @ 2017-06-08 14:33  刘冬丶  阅读(1832)  评论(0编辑  收藏  举报