数据结构算法操作试题(C++/Python)——合并两个有序链表

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——合并两个有序链表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 题目

leetcode 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/

2. 解答

python:48 ms, 10.8 MB

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:
            tmp = l2
            l2 = l1
            l1 = tmp
        p1 = l1
        while p1.next != None:
            if l2 == None:
                p1 = p1.next
                continue
            elif l2.val >= p1.val and l2.val < p1.next.val:
                p2 = ListNode(l2.val)
                p2.next = p1.next
                p1.next = p2
                l2 = l2.next
            p1 = p1.next
        p1.next = l2
        return l1 

其他方法看 leetcode 链接 评论区~