def main(): head1 = create_linked_list([4, 8, 15, 19]) head2 = create_linked_list([7, 9, 10, 16]) print("head1: " + print_linked_list(head1)) print("head2: " + print_linked_list(head2)) head1 = merge_sorted(head1, head2) print("merged (head1): " + print_linked_list(head1))
def test_palindrome(): """ 중간에 'x' 가 있는 linked list가 palindrome 인지 아닌지를 판별하는 함수를 만드세요 """ node = create_linked_list(['1', 'x', '1']) assert check_palindrome(node) node = create_linked_list(['a', 'b', 'c', 'x', 'c', 'b', 'a']) assert check_palindrome(node) node = create_linked_list(['b', 'a', 'a', 'a', 'x', 'a', 'a', 'a', 'b']) assert check_palindrome(node) node = create_linked_list(['2', 'x', '1']) assert not check_palindrome(node) node = create_linked_list(['1', 'x', '1', '1']) assert not check_palindrome(node) node = create_linked_list(['a', 'x', 'b', 'a']) assert not check_palindrome(node) node = create_linked_list(['a', 'c', 'd', 'x', 'c', 'a']) assert not check_palindrome(node) node = create_linked_list(['e', 'd', 'a', 'c', 'x', 'c', 'a']) assert not check_palindrome(node)
def test_floyd_algorithm(): """ Linked List가 순환루프라면 순환이 일어나는 지점의 Node를 리턴하는 함수를 만들어라. 만약 순환이 아니라면 None을 리턴한다. """ # Use Hash root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4) assert 4 == hash_check(root).value root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) assert hash_check(root) is None root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) assert hash_check(root) is None root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1) assert 1 == hash_check(root).value root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9) assert 9 == hash_check(root).value # Use Floyd Cycle Finding Algorithm root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4) assert 4 == floyd(root).value root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) assert floyd(root) is None root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) assert floyd(root) is None root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1) assert 1 == floyd(root).value root = create_linked_list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9) assert 9 == floyd(root).value
def test_palindrome(): """ A linked list가 주어졌을때 palindrome 인지 아닌지 알아내는 함수를 작성하세요. List: 1 -> 2 Answer: False List: 1 -> 2 -> 2 -> 1 Answer: True List: 1 -> 2 -> 1 Answer: True """ node = create_linked_list([1, 2, 2, 1]) assert palindrome_with_stack(node) is True node = create_linked_list([1, 2, 1]) assert palindrome_with_stack(node) is True node = create_linked_list([3]) assert palindrome_with_stack(node) is True node = create_linked_list([1, 2, 3, 4]) assert palindrome_with_stack(node) is False node = create_linked_list([1, 2, 2, 2]) assert palindrome_with_stack(node) is False node = create_linked_list([1, 2, 3, 2, 2]) assert palindrome_with_stack(node) is False node = create_linked_list([3, 3, 1, 3, 3, 3]) assert palindrome_with_stack(node) is False node = create_linked_list([3, 1, 1, 3, 3]) assert palindrome_with_stack(node) is False node = create_linked_list([5, 6]) assert palindrome_with_stack(node) is False
while reserved: current = reserved while current.next: if current.next.val == reserved.val: current.next = current.next.next else: current = current.next reserved = reserved.next return head if __name__ == "__main__": # For remove duplicates in a sorted linked list head = create_linked_list([1, 1, 2, 3, 4]) result = remove_duplicates_linked_list(head) print(f"New LinkedList: {traverse(result)}") # For remove duplicates in a unsorted linked list new_head = create_linked_list([1, 2, 3, 3, 2, 1]) new_result = remove_duplicates_unsorted_linked_list(new_head) print(f"New LinkedList: {traverse(new_result)}") # For remove duplicates in a unsorted linked list (two pointers, in-place) new_head_2 = create_linked_list([1, 2, 3, 3, 2, 1]) print(f"Old LinkedList: {traverse(new_head_2)}") new_result_2 = remove_duplicates_unsorted_linked_list_two_pointers( new_head_2) print(f"New LinkedList: {traverse(new_result_2)}")
def test(self): linked_list = create_linked_list([-10, -3, 0, 5, 9]) t = Solution().sortedListToBST(linked_list) bt = BinaryTree() bt.root = t self.assertListEqual([0, -10, 5, -3, 9], bt.bfs())
else: prev.next = h2 h2 = h2.next c2 = c2 - 1 prev = prev.next prev.next = h1 or h2 # Move prev to the node before cur. while c1 > 0 or c2 > 0: prev = prev.next c1 -= 1 c2 -= 1 prev.next = cur interval *= 2 return dummy.next if __name__ == "__main__": head = create_linked_list([4, 2, 1, 3]) result = sort_list_top_down(head) print(traverse(result)) head = create_linked_list([4, 2, 1, 3]) result = sort_list_bottom_up(head) print(traverse(result))
return last def reverse_between_recursion(head: ListNode, m: int, n: int) -> ListNode: """ Reverse using recursion Assuming m - 1 is the first node and the folling will be similar to reverse the previous N nodes. """ # Stop condition if m == 1: return reverse_n(head, n) # Move foward until m - 1 is 1. head.next = reverse_between_recursion(head.next, m - 1, n - 1) return head if __name__ == "__main__": head = create_linked_list([1, 2, 3, 4, 5]) new_head = reverse_between(head, 2, 4) print(traverse(new_head)) head = create_linked_list([7, 9, 2, 10, 1, 8, 6]) new_head = reverse_between(head, 3, 6) print(traverse(new_head)) head = create_linked_list([1, 2, 3, 4, 5]) new_head = reverse_between_recursion(head, 2, 4) print(traverse(new_head))
""" Recursion Time Complexity - O(N+M) - N, M are the total number of elements in the two linked lists. Space Complexity - O(N+M) - recursion stack. """ # Stop condition: when l1 or l2 is empty. if l1 is None: return l2 elif l2 is None: return l1 if l1.val <= l2.val: # Merge l1's next node and l2 as l1's new next node. l1.next = merge_two_sorted_lists_recursion(l1.next, l2) return l1 else: # Merge l2's next node and l1 as l2's new next node. l2.next = merge_two_sorted_lists_recursion(l1, l2.next) return l2 if __name__ == "__main__": l1 = create_linked_list([1, 2, 4, 5]) l2 = create_linked_list([1, 3, 4]) new_head = merge_two_sorted_lists(l1, l2) print(traverse(new_head)) l1 = create_linked_list([1, 2, 4, 5]) l2 = create_linked_list([1, 3, 4]) merged = merge_two_sorted_lists_recursion(l1, l2) print(traverse(merged))
Time Complexity - O(N) - Iterate through the list once. Space Complexty - O(1) - For pointers. """ # Use two dummy nodes to store two break-down lists. s = smaller = ListNode(-1) l = larger = ListNode(-1) while head: if head.val < x: s.next = head s = s.next else: l.next = head l = l.next head = head.next # Last node of larger is the end. l.next = None # Concatenate two lists, as smaller will be followed by larger. s.next = larger.next return smaller.next if __name__ == "__main__": head = create_linked_list([1, 4, 3, 2, 5, 2]) result = partition_list(head, 3) print(traverse(result))
Time Complexity --------------- O(N) Space Complexity ---------------- O(1) """ while head_1 and head_2: if head_1.value != head_2.value: return False head_1 = head_1.next head_2 = head_2.next return True if (head_1 is None and head_2 is None) else False # Test case for palindrome test = np.array([3, 1, 3, 1, 3]) print(test) # Reverse your linked list reversed_head = ll.reverse_linked_list(ll.create_linked_list(test)) head = ll.create_linked_list(test) # For palindrom, a linked list should be equal to its reversed version print(check_equal(head, reversed_head)) # Test case for not palindrome test = np.array([3, 3, 1, 3]) print(test) reversed_head = ll.reverse_linked_list(ll.create_linked_list(test)) head = ll.create_linked_list(test) print(check_equal(head, reversed_head))
---------- head: ``Node`` Head node of linked list. k: ``int`` Index of node relative to last node. Starts from 1. Time Complexity --------------- O(N) Space Complexity ---------------- O(1) """ # Determine length of linked list length_linked_list = ll.determine_length_linked_list(head) # Traverse ``length_linked_list`` - ``K`` nodes for _ in range(length_linked_list - k): head = head.next return head test = np.random.randint(0, 10, 10) print(test) head = ll.create_linked_list(test) ll.traverse_linked_list(head) delete_middle_node(return_k_to_last(head, 4)) ll.traverse_linked_list(head)
# Whether the linked list has even or odd number of nodes. if fast: slow = slow.next while slow: number, res = divmod(number, 10) if slow.val != res: return False slow = slow.next return True if __name__ == "__main__": head = create_linked_list([1, 2, 3, 2, 1]) print(f"Palindrome: {check_palindrome(head)}") head = create_linked_list([1, 2, 2, 1]) print(f"Palindrome: {check_palindrome(head)}") head = create_linked_list([1, 2]) print(f"Palindrome: {check_palindrome(head)}") head = create_linked_list([1, 2, 3, 2, 1]) print(f"Palindrome: {check_palindrome_array(head)}") head = create_linked_list([1, 2]) print(f"Palindrome: {check_palindrome_array(head)}") solution = Solution()
def test(self): s = BetterSolution() lst = create_linked_list([1, 2, 3, 4]) self.assertListEqual([2, 1, 4, 3], print_linked_list(s.swapPairs(lst)))
# Put the root of each list in the min heap for root in input_lists: if root: heapq.heappush(min_heap, root) # Pop the smallest element from the min heap and add it to the result sorted list. while min_heap: node = heapq.heappop(min_heap) current.next = node current = current.next # If the element poped still have next node, then add it into the heap. if node.next: heapq.heappush(min_heap, node.next) return dummy.next if __name__ == "__main__": l1 = create_linked_list([2, 6, 8]) l2 = create_linked_list([3, 6, 7]) l3 = create_linked_list([1, 3, 4]) new_list = merge_k_lists_divide_and_conquer([l1, l2, l3]) print(traverse(new_list)) l1 = create_linked_list([1, 4, 5]) l2 = create_linked_list([1, 3, 4]) l3 = create_linked_list([2, 6]) result = merge_k_sorted_lists_heapq([l1, l2, l3]) print(traverse(result))
def test(self): s = Solution() l1 = create_linked_list([9, 9]) l2 = create_linked_list([1]) result = print_linked_list(s.addTwoNumbers(l1, l2)) self.assertListEqual([0, 0, 1], result)
def test(self): l1 = create_linked_list([1, 4, 5]) l2 = create_linked_list([1, 3, 5]) l3 = create_linked_list([2, 6]) s = Solution2().mergeKLists([l1, l2, l3]) self.assertListEqual([1, 1, 2, 3, 4, 5, 5, 6], print_linked_list(s))
# If end reached and no common value encounter, this means no intersection. return False # Create 2 random arrays of unequal length. test_1 = np.random.randint(0, 10, 10) test_2 = np.random.randint(0, 10, 8) # Determine randomly if lists will match or not. intersect = bool(np.random.randint(0, 2, 1)) # Both lists will be singly linked, it follows that every node after the common # node (if present) must be the same in both linked lists. Code below implements # this logic. if intersect: intersection_pont = np.random.randint(0, 8) test_1[: 2 + intersection_pont] = np.random.randint(-10, 0, 2 + intersection_pont) test_1[2 + intersection_pont :] = test_2[intersection_pont:] # If lists do not intersect, then node values must not match at all. else: test_1 = np.random.randint(-10, 0, 10) # Create linked list print(test_1) head_1 = ll.create_linked_list(test_1) # Create linked list print(test_2) head_2 = ll.create_linked_list(test_2) # Determine if intersecting print("Lists intersect:", determine_intersection(head_1, head_2))
def test(self): s = Solution() l1 = create_linked_list([1, 2, 4]) l2 = create_linked_list([1, 3, 4]) self.assertListEqual([1, 1, 2, 3, 4, 4], print_linked_list(s.mergeTwoLists(l1, l2)))
preserve = dummy current = head.next # Current could be None, such as 1 -> 1. while current: # If the nodes have different values, move forward one step. if preserve.next.val != current.val: preserve = preserve.next current = current.next else: # If the nodes have same values, then move current node until preseve and current # pointing to different values. while current and preserve.next.val == current.val: current = current.next # Different from two pointers solution, here a.next pointing to b. preserve.next = current # Current could pointing to None after the while loop before. current = current.next if current else None return dummy.next if __name__ == "__main__": head = create_linked_list([1, 2, 3, 3, 4, 4, 5]) result = delete_duplicates(head) print(traverse(result)) head = create_linked_list([1, 2, 3, 3, 4, 4, 5]) result = delete_duplicates_three_pointers(head) print(traverse(result))
return head # Swap two nodes, head is the first node while new head is # the second node. # First we use new_head to represent the second node new_head = head.next # Then we swap the nodes after the second head and it will # be the next of head as head is moving to the position of # the original second node. head.next = swap_nodes_in_pairs_recursion(new_head.next) # Pointing new_head's next to head as new_head has become # the new first node. new_head.next = head # Return the swapped node new_head. return new_head if __name__ == "__main__": odd_list = create_linked_list([1, 2, 3, 4, 5]) print(traverse(odd_list)) new_odd_list = swap_nodes_in_pairs(odd_list) print(traverse(new_odd_list)) even_list = create_linked_list([1, 2, 3, 4]) print(traverse(even_list)) new_even_list = swap_nodes_in_pairs(even_list) print(traverse(new_even_list)) result = swap_nodes_in_pairs_recursion(new_even_list) print(traverse(result))