add = 0 while True: if l1: left = l1.val l1 = l1.next else: left_finish = True left = 0 if l2: right = l2.val l2 = l2.next else: right_finish = True right = 0 if left_finish == right_finish == True and not add: break tmp = (left + right + add) if tmp >= 10: result.next = ListNode(tmp - 10) add = 1 else: result.next = ListNode(tmp) add = 0 result = result.next return first.next if __name__ == "__main__": left = ListNode.list2chain([5]) right = ListNode.list2chain([5]) print Solution().addTwoNumbers(left, right)
class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = ListNode(0) tmp = result while (l1 is not None) and (l2 is not None): if l1.val > l2.val: tmp.next = l2 l2 = l2.next else: tmp.next = l1 l1 = l1.next tmp = tmp.next if l1 is None: tmp.next = l2 else: tmp.next = l1 return result.next if __name__ == "__main__": l1 = ListNode.list2chain([1, 2, 4]) l2 = ListNode.list2chain([1, 3, 4]) print Solution().mergeTwoLists(l1, l2)