445.Add Two Numbers II

Tags: [linked_list], [stack]

Link: https://leetcode.com/problems/add-two-numbers-ii/?tab=Description

You are given twonon-emptylinked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input:
 (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)

Output:
 7 -> 8 -> 0 -> 7

Solution: stack

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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        stack1 = []
        stack2 = []

        while l1:
            stack1.append(l1)
            l1 = l1.next
        while l2:
            stack2.append(l2)
            l2 = l2.next

        rest_stack = []
        carry = 0
        while stack1 and stack2:
            curr1 = stack1.pop()
            curr2 = stack2.pop()
            tmp_sum = curr1.val + curr2.val + carry

            if tmp_sum < 10:
                rest_stack.append(tmp_sum)
                carry = 0
            else:
                rest_stack.append(tmp_sum % 10)
                carry = tmp_sum / 10

        while stack1:
            curr = stack1.pop()
            tmp_sum = curr.val + carry

            if tmp_sum < 10:
                rest_stack.append(tmp_sum)
                carry = 0
            else:
                rest_stack.append(tmp_sum % 10)
                carry = tmp_sum / 10

        while stack2:
            curr = stack2.pop()
            tmp_sum = curr.val + carry

            if tmp_sum < 10:
                rest_stack.append(tmp_sum)
                carry = 0
            else:
                rest_stack.append(tmp_sum % 10)
                carry = tmp_sum / 10

        if carry:
            rest_stack.append(carry)

        # build the result linked list
        feak_head = ListNode(-1)
        tmp = feak_head
        while rest_stack:
            tmp.next = ListNode(rest_stack.pop())
            tmp = tmp.next

        return feak_head.next

Revelation:

  • When we need the reversed sequence, and the sequence cannot be changed, we can think about using the stack.

Note:

  • Time complexity = O(max(n, m)), n is the number of nodes in list1, m is the number of nodes in list2.

results matching ""

    No results matching ""