c1 = list1.head c2 = list2.head merged = LinkedList() if c1.value < c2.value: merged.head = c1 c1 = c1.next else: merged.head = c2 c2 = c2.next c3 = merged.head while c1 and c2: if c1.value < c2.value: c3.next = c1 c3 = c3.next c1 = c1.next else: c3.next = c2 c3 = c3.next c2 = c2.next c3.next = c1 if c1 else c2 return merged if __name__ == '__main__': list1 = linked_list.create_linked_list([0, 1, 4, 5]) list2 = linked_list.create_linked_list([-1, 2, 6, 7, 8]) print merge(list1, list2) print merge_no_extra_space(list1, list2)
""" Merge k sorted linked lists and return it as one sorted list. """ from implementations import heap from implementations import linked_list from implementations.linked_list import LinkedList def sort_k_linked_lists(*linked_lists): min_heap = heap.Heap(comp=lambda x, y: x.value < y.value) for lst in linked_lists: min_heap.insert(lst.head) result = LinkedList() while len(min_heap.items) > 0: item = min_heap.extract_min() if item.next: min_heap.insert(item.next) result.add(item.value) return result if __name__ == "__main__": l1 = linked_list.create_linked_list([-3, 0, 1, 2, 6, 7]) l2 = linked_list.create_linked_list([2, 4, 5, 10]) l3 = linked_list.create_linked_list([1, 7, 9]) print sort_k_linked_lists(l1, l2, l3)
from implementations import linked_list def remove_linked_list_duplicates(llist): if llist.head is None or llist.head.next is None: return llist prev = llist.head curr = prev.next first_dupe = None in_dupe = False while curr is not None: if prev.value != curr.value: if in_dupe: first_dupe.next = curr curr.prev = first_dupe in_dupe = False elif not in_dupe: first_dupe = prev in_dupe = True prev = curr curr = curr.next if in_dupe: first_dupe.next = None return llist if __name__ == '__main__': llist = linked_list.create_linked_list([1, 1, 2, 2, 3, 4, 5, 5, 5, 5, 6, 7, 8, 10, 10]) print remove_linked_list_duplicates(llist)
while end.next is not None: end = end.next i = lst.head while i != end: j = end.next end.next = i tmp = i.next i.next = j i = tmp lst.head = end return lst def reverse2(lst): new_head = None while lst.head is not None: next_node = lst.head.next lst.head.next = new_head new_head = lst.head lst.head = next_node lst.head = new_head return lst if __name__ == '__main__': llist = linked_list.create_linked_list(range(10)) print reverse2(llist)