def mergeTwoSortedLists(l1, l2): if not l1: return l2 if not l2: return l1 if not l1 and not l2: return None ll = DoublyLinkedList() cur_l1 = l1.head cur_l2 = l2.head index = 0 max_length = l1.length + l2.length while index < max_length: if cur_l1 and cur_l2: if cur_l1.value <= cur_l2.value: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next else: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next elif cur_l1 and not cur_l2: ll.addAtIndex(index, cur_l1.value) cur_l1 = cur_l1.next elif cur_l2 and not cur_l1: ll.addAtIndex(index, cur_l2.value) cur_l2 = cur_l2.next index += 1 return ll
def addingTwoNumbers(l1, l2): l1_values = [] l2_values = [] while l1.head or l2.head: if l1.head: l1_values.append(str(l1.head.value)) l1.head = l1.head.next if l2.head: l2_values.append(str(l2.head.value)) l2.head = l2.head.next sum_result = int("".join(l1_values[::-1])) + int("".join(l2_values[::-1])) sum_result = list(str(sum_result)) ll = DoublyLinkedList() index = 0 for i in range(len(sum_result) - 1, -1, -1): ll.addAtIndex(index, sum_result[i]) index += 1 return ll