剑指Offer25-合并两个排序的链表

剑指Offer25-合并两个排序的链表

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:


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

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

限制:


0 <= 链表长度 <= 1000

来源:力扣(LeetCode)

链接:力扣

一解

判定两个节点“val”,将小的一方放到尾结点的“next”中:


# Definition for singly-linked list.

# class ListNode:

#     def __init__(self, x):

#         self.val = x

#         self.next = None

# Definition for singly-linked list.

# class ListNode:

#     def __init__(self, x):

#         self.val = x

#         self.next = None

class Solution:

    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:

        if not l1:

            return l2

        if not l2:

            return l1

        if l2.val > l1.val:

            head = l1

            l1 = l1.next

        else:

            head = l2

            l2 = l2.next

        tmp = head

        while l1 and l2:

            if l2.val > l1.val:

                tmp.next = l1

                l1 = l1.next

            else:

                tmp.next = l2

                l2 = l2.next

            tmp = tmp.next

        tmp.next = l1 if l1 else l2

        return head

二解

思路与“一解”相同,“二解”使用额外结点“ListNode(0)”减少代码量:


# Definition for singly-linked list.

# class ListNode:

#     def __init__(self, x):

#         self.val = x

#         self.next = None

class Solution:

    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:

        head = tmp = ListNode(0)

        while l1 and l2:

            if l2.val > l1.val:

                tmp.next, l1 = l1, l1.next

            else:

                tmp.next, l2 = l2, l2.next

            tmp = tmp.next

        tmp.next = l1 if l1 else l2

        # 注意:结果返回 head.next

        return head.next

1 个赞
class ListNode:
    def __init__(self, x, next_node=None):
        self.val = x
        self.next = next_node

    @property
    def value(self):
        result = []
        node = self
        while node:
            result.append(node.val)
            node = node.next
        return result


class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val <= l2.val:
            head = l1
            l1.next = self.mergeTwoLists(l1.next, l2)
        else:
            head = l2
            l2.next = self.mergeTwoLists(l1, l2.next)
        return head


if __name__ == '__main__':
    l1 = ListNode(1, ListNode(2, ListNode(4)))
    l2 = ListNode(1, ListNode(2, ListNode(3)))
    print(Solution().mergeTwoLists(l1, l2).value)

递归求解一波