def partition(ll, value): # make a new linked list with a tail to hold high values and head to hold the small values # O(n) time but O(n) for space for new linked list output_ll = LinkedList() output_ll.tail = output_ll.head current = ll.head while current: if current.value < value: if not output_ll.head: output_ll.head = Node(current.value) output_ll.tail = output_ll.head else: new_node = Node(current.value) new_node.next = output_ll.head output_ll.head = new_node else: #add to the tail if not output_ll.tail: output_ll.tail = Node(current.value) output_ll.head = output_ll.tail else: new_node = Node(current.value) output_ll.tail.next = new_node output_ll.tail = new_node current = current.next return output_ll
def sum_lists(ll_1, ll_2): if not ll_1.head or not ll_2.head: return "ll does not have head" ll = LinkedList() current_1 = ll_1.head current_2 = ll_2.head carry_over = 0 while current_1 and current_2: sum = current_1.value + current_2.value + carry_over if sum > 9: new_value = sum - 10 carry_over = 1 else: new_value = sum carry_over = 0 if not ll.head: ll.head = Node(new_value) ll.tail = ll.head else: ll.tail.next = Node(new_value) ll.tail = ll.tail.next current_1 = current_1.next current_2 = current_2.next while current_1: sum = current_1.value + carry_over if sum > 9: new_value = sum - 10 carry_over = 1 else: new_value = sum carry_over = 0 ll.tail.next = Node(new_value) ll.tail = ll.tail.next current_1 = current_1.next while current_2: sum = current_2.value + carry_over if sum > 9: new_value = sum - 10 carry_over = 1 else: new_value = sum carry_over = 0 ll.tail.next = Node(new_value) ll.tail = ll.tail.next current_2 = current_2.next if carry_over: ll.tail.next = Node(carry_over) ll.tail = ll.tail.next return ll
def sum_lists2(ll_1, ll_2): if not ll_1.head or not ll_2.head: return "ll does not have head" ll = LinkedList() current_1 = ll_1.head current_2 = ll_2.head carry_over = 0 def get_new_value(sum, carry_over): if sum > 9: new_value = sum - 10 carry_over = 1 else: new_value = sum carry_over = 0 return new_value, carry_over def add_to_tail(new_value): ll.tail.next = Node(new_value) ll.tail = ll.tail.next while current_1 and current_2: sum = current_1.value + current_2.value + carry_over new_value, carry_over = get_new_value(sum, carry_over) if not ll.head: ll.head = Node(new_value) ll.tail = ll.head else: add_to_tail(new_value) current_1 = current_1.next current_2 = current_2.next if current_1: remaining = current_1 else: remaining = current_2 while remaining: sum = remaining.value + carry_over new_value, carry_over = get_new_value(sum, carry_over) add_to_tail(new_value) remaining = remaining.next if carry_over: ll.tail.next = Node(carry_over) ll.tail = ll.tail.next return ll