def sum_lists(l1, l2, carry): """ You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (7-> 1 -> 6) + (5 -> 9 -> 2).That is,617 + 295. Output: 2 -> 1 -> 9. That is, 912. Input: (8-> 3) + (1 -> 1 -> 2).That is,211 + 38. Output: 9 -> 4 -> 2. That is, 249. :param l1: List 1 :param l2: List 2 :param carry: Carry over the sum in the current execution thread :return: """ if not l1 and not l2 and carry == 0: return new_list = LinkedList() node_sum = carry + (l1.value() if l1 else 0) + (l2.value() if l2 else 0) new_list.add_last(node_sum % 10) result = sum_lists(l1.next() if l1 else None, l2.next() if l2 else None, node_sum // 10) new_list.add_last(result) if result else None return new_list
def partition(l_list, part_key): """ Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. :param l_list: Linked List to be partitioned :param part_key:Key around which the linked list should be partitioned :return: Reference to the newly created list """ if not l_list: return left_start = left_end = right_start = None curr = l_list.head() left_start = LinkedList() right_start = LinkedList() while curr: if curr.value() < part_key: left_start.add_last(curr) else: right_start.add_last(curr) curr = curr.next() if not left_start.empty(): left_end = left_start.tail() left_end._next = right_start.head() return left_start if not left_start.empty() else right_start