Пример #1
0
    - Once the fast node.next is null, return slow node data
"""

from LinkedList.singlyLL import SinglyLL


def find_middle(head):
    """ Find middle element in a linkedlist """
    slow_node = head
    fast_node = head
    """taking fast_node not none condition to
    prevent nontype error in case of even number
    of nodes.
    """
    while fast_node and fast_node.next is not None:
        slow_node = slow_node.next
        fast_node = fast_node.next.next

    return slow_node.data


if __name__ == '__main__':
    sll = SinglyLL()

    for i in range(0, 10):
        sll.append(i)

    print(sll.display())

    print(find_middle(sll.head))
Пример #2
0
        prev_node = cur_node
        cur_node = cur_node.next
        if cur_node not in node_list:
            node_list.append(cur_node)
        else:
            print('Loop Detected')
            prev_node.next = None
            return

    print('No Loop detected')


if __name__ == '__main__':
    ll = SinglyLL()
    for i in range(0, 10):
        ll.append(i)
    print(ll.display())
    detect_remove_loop(ll.head)

    print('Creating a linked list with loop')
    ll2 = SinglyLL()
    create_ll_with_loop(ll2)
    # print('infinite loop')
    # ll2.display()
    print('running LL with loop')

    detect_remove_loop(ll2.head)
    cur_node = ll2.head
    while cur_node is not None:
        print(cur_node.data)
        cur_node = cur_node.next
Пример #3
0
def remove_dup_sorted_list(head):
    """ remove duplicate elements from a sorted list """
    cur_node = head

    while cur_node.next is not None:
        prev_node = cur_node
        cur_node = cur_node.next
        if cur_node.data == prev_node.data:
            prev_node.next = cur_node.next


if __name__ == '__main__':
    print('Removing Dups from an unsorted list')
    sll = SinglyLL()
    sll.append(2)
    sll.append(3)
    sll.append(4)
    sll.append(2)
    sll.append(5)
    sll.append(3)

    print(sll.display())

    remove_dup(sll.head)

    print(sll.display())

    print('*' * 10)

    print('Removing dups from a sorted list')
Пример #4
0
        prev = l3.next
           
     
        if l1 is not None:
            l1 = l1.next
        if l2 is not None:
            l2 = l2.next

    if carry < 0:
        l3.append(carry)

    print(l3.display())
            
if __name__ == '__main__':
    l1 = SinglyLL()
    l1.append(3)
    l1.append(4)
    l1.append(5)
    print(l1.display())

    l2 = SinglyLL()
    l2.append(2)
    l2.append(5)
    l2.append(9)
    l2.append(8)
    print(l2.display())
  
    l3 = SinglyLL()
    add_two_numbers(l1.head, l2.head, l3.head)