Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 948 Bytes

21.md

File metadata and controls

51 lines (39 loc) · 948 Bytes

Merge Two Sorted Lists

Description

link


Solution

See Code


Code

O(n)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        if not l2:
            return l1
        
        pos1, pos2 = l1, l2
        head = node = ListNode(0)
        while pos1 and pos2:
            if pos1.val <= pos2.val:
                node.next = pos1
                pos1 = pos1.next
            else:
                node.next = pos2
                pos2 = pos2.next
            node = node.next
            
        node.next = pos2 if not pos1 else pos1
        return head.next