美文网首页
算法---链接两个有序链表

算法---链接两个有序链表

作者: reedthinking | 来源:发表于2017-07-17 23:25 被阅读0次

给定两个有序链表,链接他们,元素从小到大排列

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'thinkreed'
__mtime__ = '2017/3/23'

"""

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val < l2.val:
            #l1需要去链接后续节点
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            #l2去链接后续节点
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

相关文章

网友评论

      本文标题:算法---链接两个有序链表

      本文链接:https://www.haomeiwen.com/subject/irfckxtx.html