예제 #1
0
def merge(a, b):
    '''
    Merges two linked list sorting data in the nodes
    Returns a list_merged linked list
    '''
    list_merged = SinglyLinkedList()
    list_merged.prepend(Node(
        0))  # Add a fake head that is discarted later to avoid empty lists
    current = list_merged.head
    a_head = a.head
    b_head = b.head

    # Iterate over each node until we reach the tail one and build the list by updating the current next node
    while a_head != None or b_head != None:
        if a_head is None:
            current.next = b_head
            b_head = b_head.next
        elif b_head is None:
            current.next = a_head
            a_head = a_head.next
        else:
            if a_head.data < b_head.data:
                current.next = a_head
                a_head = a_head.next
            else:
                current.next = b_head
                b_head = b_head.next
        current = current.next

    # Discard fake head and set first list_merged node as head
    list_merged.head = list_merged.head.next
    return list_merged
예제 #2
0
def reverse(l: ll):
    curr = l.head
    prev = None

    while curr.next:
        next_element = curr.next
        curr.next = prev
        prev = curr
        curr = next_element

    l.head = curr
    l.head.next = prev
    return l
예제 #3
0
def split(list):
    '''
    Splits a linked list into two new ones right in the middle or None in the right if it has 1 node only
    '''
    left = SinglyLinkedList()
    right = SinglyLinkedList()

    if list is None or list.head is None:
        left = list
        right = None
    else:
        mid_point = list.size() // 2
        mid_node = list.node_at_index(mid_point - 1)
        left = list
        right.head = mid_node.next
        mid_node.next = None
    return left, right
예제 #4
0
    len1, len2 = len(self), len(ll2)
    node1, node2 = self.head, ll2.head
    if len1 > len2:
        for i in range(len1 - len2):
            node1 = node1.next
    elif len2 > len1:
        for i in range(len2 - len1):
            node2 = node2.next

    while node1 is not node2:
        node1, node2 = node1.next, node2.next
    
    return node1


SinglyLinkedList.has_intersection = has_intersection

if __name__ == "__main__":
    ll1 = SinglyLinkedList([1,2,3])
    ll2 = SinglyLinkedList()
    ll2.head = ll1.head.next.next
    print(ll1.has_intersection(ll2).value)
    ll3 = SinglyLinkedList([1,2])
    print(ll1.has_intersection(ll3))
    ll4 = None
    print(ll1.has_intersection(ll4))
    ll5 = SinglyLinkedList()
    print(ll1.has_intersection(ll5))