total += b_curr.data b_curr = b_curr.next sum_ll.add_node(Node(total%10)) carryover = total/10 if carryover: sum_ll.add_node(Node(carryover)) return sum_ll if __name__ == '__main__': a = LinkedList(Node(7, Node(1, Node(6)))) b = LinkedList(Node(5, Node(9, Node(2)))) print a.as_string() print b.as_string() print "adding the lists (617 + 295 = 912) my two ways: " print sum_lists(a, b).as_string() print alt_sum_lists(a, b).as_string() print "uneven lists: 17 + 295 = 312" c = LinkedList(Node(7, Node(1))) d = LinkedList(Node(5, Node(9, Node(2)))) print c.as_string() print d.as_string() print sum_lists(c, d).as_string()
if current.next == None: #check if we are on last node previous.next = None else: current.data = current.next.data current.next = current.next.next # move to next previous = current current = current.next # if not in dict - this isn't a dup. add it to dict and move on else: nodes_seen.setdefault(current.data, True) previous = current current = current.next return ll my_list = LinkedList(Node(2, Node(4, Node(1, Node(2, Node(7, Node(1))))))) print "testing having to remove last node" print "my_list before: ", my_list.as_string() remove_dups(my_list) print "my_list after: ", my_list.as_string() print "testing not having to remove last node: " another_list = LinkedList(Node(4, Node(4, Node(1, Node(2, Node(7)))))) print "another_list before: ", another_list.as_string() remove_dups(another_list) print "another_list after: ", another_list.as_string()
output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 (or similar, order within greater or lesser doesn't matter) """ # create list of all nodes >= to partition value move_list = [] # go through our LL and take out the nodes >= and add to our move_list current = ll.head while current: if current.data >= x: move_node = Node(current.data) move_list.append(move_node) current.data = current.next.data current.next = current.next.next else: current = current.next for n in move_list: ll.add_node(n) my_ll = LinkedList(Node(3, Node(5, Node(8, Node(5, Node(9, Node(2, Node(1)))))))) print my_ll.as_string() partition(my_ll, 5) print my_ll.as_string()