Exemplo n.º 1
0
def test_merge_two_sorted_lists():
    from leetcode.structures.singly_linked_list import ListNode

    s = Solution()
    l1 = ListNode.from_list([1, 2, 3], reversed=False)
    l2 = ListNode.from_list([2, 3, 5], reversed=False)
    assert str(s(l1, l2)) == "[ 1 2 2 3 3 5 ]"
Exemplo n.º 2
0
def test_creation_from_list_reveresed():
    from leetcode.structures.singly_linked_list import ListNode

    s = Solution()
    l1 = ListNode.from_list([], reversed=False)
    l2 = ListNode.from_list([2, 3, 5], reversed=False)
    assert str(s(l1, l2)) == "[ 2 3 5 ]"
Exemplo n.º 3
0
    def __call__(self, l1, l2):
        def gen_add(a, b):
            """generator based solution"""
            carry = 0
            while a and b:
                lsum = a.val + b.val + carry
                carry = lsum // 10
                yield ListNode(lsum % 10)
                a, b = a.next, b.next

            r = a or b

            while carry > 0:
                if r:
                    lsum = carry + r.val
                    carry = lsum // 10
                    yield ListNode(lsum % 10)
                    r = r.next
                else:
                    yield ListNode(carry)
                    carry = 0
            yield r
            r = None

        head = ListNode(0)
        curr = head

        for node in gen_add(l1, l2):
            curr.next = node
            curr = curr.next
        return head.next
Exemplo n.º 4
0
        def gen_add(a, b):
            """generator based solution"""
            carry = 0
            while a and b:
                lsum = a.val + b.val + carry
                carry = lsum // 10
                yield ListNode(lsum % 10)
                a, b = a.next, b.next

            r = a or b

            while carry > 0:
                if r:
                    lsum = carry + r.val
                    carry = lsum // 10
                    yield ListNode(lsum % 10)
                    r = r.next
                else:
                    yield ListNode(carry)
                    carry = 0
            yield r
            r = None
Exemplo n.º 5
0
    def __call__(self, l1, l2):
        if not (l1 or l2):
            return ListNode(None)

        head = ListNode(0)
        curr = head
        while l1 and l2:
            if l1.val < l2.val:
                node = ListNode(l1.val)
                l1 = l1.next
            else:
                node = ListNode(l2.val)
                l2 = l2.next
            curr.next = node
            curr = node
        if not l1:
            curr.next = l2

        elif not l2:
            curr.next = l1

        return head.next
def test_creation_from_list():
    from leetcode.structures.singly_linked_list import ListNode

    node = ListNode.from_list([1, 2, 3], reversed=False)
    assert str(node) == "[ 1 2 3 ]"