def find_nth_to_last(root, nth): if root is None or nth < 0: return None p2 = root for x in xrange(0, nth): p2 = p2.next if p2 is None: return None p1 = root while p2.next is not None: p1 = p1.next p2 = p2.next return p1 root = Node(0) root.append_to_tail(1) root.append_to_tail(2) root.append_to_tail(3) root.append_to_tail(4) root.append_to_tail(5) root.append_to_tail(6) root.append_to_tail(7) root.append_to_tail(8) root.append_to_tail(9) print_nodes(root) nth = 2 node = find_nth_to_last(root, nth) print "%s to last: %s" % (nth, node.data)
runner = root while runner is not current: if runner.data == current.data: tmp = current.next previous.next = tmp current = tmp break runner = runner.next if runner is current and runner is not None: previous = current current = current.next root = Node(4) root.append_to_tail(4) root.append_to_tail(4) root.append_to_tail(5) root.append_to_tail(8) root.append_to_tail(7) root.append_to_tail(8) root.append_to_tail(9) root.append_to_tail(9) root.append_to_tail(9) root.append_to_tail(10) root.append_to_tail(8) root.append_to_tail(10) print_nodes(root) remove_duplicates(root) print_nodes(root)
root1 = root1.next mult *= 10 num2 = 0 mult = 1 while root2 is not None: num2 += root2.data * mult root2 = root2.next mult *= 10 result = num1 + num2 print "%s + %s = %s" % (num1, num2, result) result_list = None for x in str(result)[::-1]: if result_list is None: result_list = Node(x) else: result_list.append_to_tail(x) return result_list root1 = Node(3) root1.append_to_tail(1) root1.append_to_tail(5) root1.append_to_tail(6) root2 = Node(5) root2.append_to_tail(9) root2.append_to_tail(2) result = sum_linked_lists(root1, root2) print_nodes(result)