Beispiel #1
0
def partition(l_list, part_key):
    """
    Write code to partition a linked list around a value x, such that all nodes less than x come
    before all nodes greater than or equal to x. If x is contained within the list the values of x only need
    to be after the elements less than x (see below). The partition element x can appear anywhere in the
    "right partition"; it does not need to appear between the left and right partitions.
    :param l_list: Linked List to be partitioned
    :param part_key:Key around which the linked list should be partitioned
    :return: Reference to the newly created list
    """
    if not l_list:
        return
    left_start = left_end = right_start = None

    curr = l_list.head()
    left_start = LinkedList()
    right_start = LinkedList()
    while curr:
        if curr.value() < part_key:
            left_start.add_last(curr)
        else:
            right_start.add_last(curr)
        curr = curr.next()

    if not left_start.empty():
        left_end = left_start.tail()
        left_end._next = right_start.head()
    return left_start if not left_start.empty() else right_start
Beispiel #2
0
def is_palindrome_stack(l_list: LinkedList):
    """
    Implement the algorithm to check if the linked list is a palindrome using a stack
    Use the Fast Pointer, Slow pointer technique to insert the first half of the list in the stack,
    pop an item off the stack and traverse through the remaining list to see if they match.
    1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1 - True
    1 -> 2 -> 3 -> 4 -> 4 -> 3 -> 2 -> 1 - True
    :param l_list: Linked list
    :return: True if the list is a palindrome, False otherwise
    """
    if not l_list or l_list.empty():
        return False
    # Traverse through the first half of the list and add to the stack
    stack = []
    slow = l_list.head()
    fast = l_list.head()

    while fast and fast.next():
        stack.append(slow.value())
        slow = slow.next()
        fast = fast.next().next()

    if fast:  # If there are odd number of elements in the list, the fast pointer is not null
        slow = slow.next()
    # Start popping from the stack and compare against the remaining elements in the list using the slow pointer
    while slow:
        item = stack.pop()
        if not item == slow.value():
            return False
        slow = slow.next()

    return True