Premiumlab  

https://leetcode.com/problems/add-two-numbers/#/description

 

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

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

 

 

Sol:

 

# 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
        """
        # Initialize current node to dummy head of the returning list. 
        dummyhead = ListNode(0)
        # Initialize pp and qq to head of l1l1 and l2l2 respectively.
        p, q, curr = l1, l2, dummyhead
        # Initialize carry to 0.
        carry = 0
        
        # Loop through lists l1 and l2 until you reach both ends.
        while p or q:
            # Set x to node p's value. If p has reached the end of l1, set to 0.
            if p:
                x = p.val
            else:
                x = 0
            # Set y to node q's value. If q has reached the end of l2, set to 0.
            if q:
                y = q.val
            else:
                y = 0
            # Set sum = x + y + carrys.
            digit = carry + x + y
            # Update carry = sum / 10.
            carry = digit/10
            # Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
            curr.next = ListNode(digit % 10)
            curr = curr.next
            # Advance both p and q.
            if p:
                p = p.next
            if q:
                q = q.next
        # Check if carry =1, if so append a new node with digit 1 to the returning list.        
        if carry > 0:
            curr.next = ListNode(carry)
            
        # Return dummy head's next node.
        return dummyhead.next

 

posted on 2017-07-25 17:08  Premiumlab  阅读(122)  评论(0编辑  收藏  举报