def sum_lists_followup(ll_a, ll_b): # Pad the shorter list with zeros if length_list(ll_a) < length_list(ll_b): for i in range(length_list(ll_b) - length_list(ll_a)): ll_a.add_to_beginning(0) else: for i in range(length_list(ll_a) - length_list(ll_b)): ll_b.add_to_beginning(0) # Find sum n1, n2 = ll_a.head, ll_b.head result = 0 while n1 and n2: result = (result * 10) + n1.data + n2.data n1 = n1.next n2 = n2.next # Create new linked list ll = SLL.SingleLinkList() for i in str(result): ll.appendRight(i) return ll
def add_list(S1, S2): if S1 is None: return S2 if S2 is None: return S1 if S1 is None and S2 is None: return None S = SLL.SingleLinkList() carry = 0 head1, head2 = S1.head, S2.head while head1 or head2: result = carry if head1: result += head1.data if head2: result += head2.data S.appendRight(result % 10) carry = result // 10 head1 = head1.next head2 = head2.next if carry: S.appendRight(carry) return S
n1, n2 = ll_a.head, ll_b.head result = 0 while n1 and n2: result = (result * 10) + n1.data + n2.data n1 = n1.next n2 = n2.next # Create new linked list ll = SLL.SingleLinkList() for i in str(result): ll.appendRight(i) return ll S1 = SLL.SingleLinkList() S1.appendRight(7) S1.appendRight(1) S1.appendRight(6) S2 = SLL.SingleLinkList() S2.appendRight(5) S2.appendRight(9) S2.appendRight(2) # S = add_list(S1, S2) # S.print_list() S1 = SLL.SingleLinkList() S1.appendRight(6) S1.appendRight(1) S1.appendRight(7) S2 = SLL.SingleLinkList() S2.appendRight(5)
def partion_list_opt2(S, x): node = S.tail = S.head while node: next = node.next node.next = None if node.data < x: node.next = S.head S.head = node else: S.tail.next = node S.tail = node node = next # Error check in case all nodes are less than x if S.tail.next is not None: S.tail.next = None S = SLL.SingleLinkList() S.appendRight(3) S.appendRight(5) S.appendRight(8) S.appendRight(5) S.appendRight(10) S.appendRight(2) S.appendRight(1) # S.head = partition_list_opti(S.head, 5) partion_list_opt2(S, 5) S.print_list()