leetcode 2 add two numbers
常规数字加法
#2017/03/12
# practise on leetcode
# Definition for singly-linked list.
class Solution:
def addTwoNumbers(self, l1, l2):
ans = ListNode(0)
temp_ans = ans
temp_l1 = l1
temp_l2 = l2
while temp_l1 or temp_l2:
temp_ans.val = temp_ans.val + self._add_nodes(temp_l1, temp_l2)
if temp_ans.val < 10:
if temp_l1 and temp_l1.next or temp_l2 and temp_l2.next:
temp_ans.next = ListNode(0)
else:
temp_ans.next = ListNode(1)
temp_ans.val -= 10
if temp_l1:
temp_l1 = temp_l1.next
if temp_l2:
temp_l2 = temp_l2.next
temp_ans = temp_ans.next
return ans
def _add_nodes(self, node1, node2):
# if not node1 and not node2:
# raise Exception("Two nodes are None")
try:
if not node1:
return node2.val
if not node2:
return node1.val
except:
print("Two nodes are None.")
return 0
if node1 and node2:
return node1.val + node2.val