if next.value in existing_values: node.next = next.next else: node = node.next existing_values.add(node.value) def remove_duplicates_constant_memory(node): while not node is None: before_check = node check = node.next while not check is None: if check.value == node.value: before_check.next = check.next check = check.next else: before_check = check check = check.next node = node.next head = get_dummy_list() remove_duplicates(head) assert to_string(head) == '1,2,3,4' head = get_dummy_list() remove_duplicates_constant_memory(head) assert to_string(head) == '1,2,3,4'
from linkedlist import get_dummy_list from linkedlist import to_string def remove(node): node.value = node.next.value node.next = node.next.next head = get_dummy_list() remove(head.next) assert '1,3,2,4,1' == to_string(head)
if result['depth'] <= k: result['node'] = node return result def get_last_values_iteratively(k, node): runner = node runner_headstart = 0 while not runner is None and runner_headstart < k: runner = runner.next runner_headstart += 1 if runner_headstart < k: return node while not runner is None: runner = runner.next node = node.next return node head = get_dummy_list() assert '' == to_string(get_last_values(0, head)['node']) assert '2,4,1' == to_string(get_last_values(3, head)['node']) assert '1,2,3,2,4,1' == to_string(get_last_values(20, head)['node']) assert '' == to_string(get_last_values_iteratively(0, head)) assert '2,4,1' == to_string(get_last_values_iteratively(3, head)) assert '1,2,3,2,4,1' == to_string(get_last_values_iteratively(20, head))