leetcode 21 python 合并两个有序链表

传送门

题目要求

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

思路一

遍历2个链表,按大小顺序构建一个新的有序链表

→_→ talk is cheap, show me the code

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        p, q = l1, l2
        m = n = ListNode(0)
        while p and q:
            if p.val <= q.val:
                n.next = p
                p = p.next
            else:
                n.next = q
                q = q.next
            n = n.next
        n.next = q or p
        return m.next
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容