Merge two sorted linked lists:

"""
 Merge two linked lists
 head could be None as well for empty list
 Node is defined as

 class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
    if headA is None:
        return headB
    if headA is None:
        return headA

    # create dummy node to avoid additional checks in loop
    s = t = Node() 
    while not (headA is None or headB is None):
        if headA.data < headB.data:
            # remember current low-node
            c = headA
            # follow ->next
            headA = headA.next
        else:
            # remember current low-node
            c = headB
            # follow ->next
            headB = headB.next

        # only mutate the node AFTER we have followed ->next
        t.next = c          
        # and make sure we also advance the temp
        t = t.next

    t.next = headA or headB

    # return tail of dummy node
    return s.next

results matching ""

    No results matching ""