Merge two sorted linked lists

  • + 0 comments
    def mergeLists(head1, head2):
        ptr = ret = opposite = None
        if head1.data < head2.data:
            ptr = head1
            ret = head1
            opposite = head2
        else:
            ptr = head2
            ret = head2
            opposite = head1
        
        while ptr:
            while ptr.next and ptr.next.data < opposite.data:
                ptr = ptr.next
            
            next_p = ptr.next
            ptr.next = opposite
            ptr = opposite
            opposite = next_p
    
            if opposite is None:
                return ret