コード例 #1
0
ファイル: reverse.py プロジェクト: Jsgoller1/Hishuv
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.")
コード例 #2
0
ファイル: merge.py プロジェクト: Jsgoller1/Hishuv
        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))