Esempio n. 1
0
def delete_duplicates(head):
    seen_values = {}
    my_node = head
    prev = None
    while my_node != None:
        try:
            x = seen_values[my_node.value] # If we don't get a key error here, we've seen the val before, so remove it.
            prev.Next = my_node.Next
            my_node = my_node.Next
        except KeyError:
            seen_values[my_node.value] = True
            prev = my_node
            my_node = my_node.Next
    return head


if __name__ == "__main__":
    vals = [1,2,3,4,3,5,6,1,7,8,9,3,10,2,11]
    head = node()
    my_node = head
    for each in vals:
        my_node.value = each
        if each != vals[-1]:
            my_node.Next = node()
            my_node = my_node.Next
    print("Linked list before deletions:")
    print(traverse(head, False))
    head = delete_duplicates(head)
    print("Linked list after deletions:")
    print(traverse(head, False))
Esempio n. 2
0
import linked_lists
import random

def reverse(head, info=True):
    if(info):
        print("Linked list reversal")
        print("Time complexity: O(n)")
        print("Space complexity: O(1)")
    try:
        assert(isinstance(head, linked_lists.node))
    except AssertionError:
        return False
    prev = None
    while(head != None):
        following = head.Next
        head.Next = prev
        prev = head
        head = following
    return prev

if __name__ == '__main__':
    myList = linked_lists.set_up(random.randint(1,20))
    repl = True
    while(repl != "q"):
        print linked_lists.traverse(myList)
        myList = reverse(myList)
        repl = raw_input("Press any key to continue, or \"q\" to quit.")
Esempio n. 3
0
        if a_head.value > b_head.value:
            current.value = b_head.value
            b_head = b_head.Next
        else: # a_head.value <= b_head.value
            current.value = a_head.value
            a_head = a_head.Next
        new_node = linked_lists.node()
        current.Next = new_node
        current = new_node

    # One of the lists was empty, so shallow-copy the rest of the other
    non_empty = a_head or b_head
    if non_empty:
        current.value = non_empty.value # resolve dangling value
        current.Next = non_empty.Next # append and finish
    else: # this happens only when both were passed in as None
        head = None

    return head

if __name__ == '__main__':
    len_ll_a = random.randint(1,20)
    ll_a = linked_lists.set_up(len_ll_a)
    len_ll_b = random.randint(1,20)
    ll_b = linked_lists.set_up(len_ll_b)
    print "Length of List A: " + str(len_ll_a)
    print "List A: " + str(linked_lists.traverse(ll_a, False))
    print "Length of List B: " + str(len_ll_b)
    print "List B: " + str(linked_lists.traverse(ll_b, False))
    print "AB (merge of A and B): " + str(linked_lists.traverse(merge_shallow(ll_a, ll_b, False), False))