Merge two linked lists in Python
Elegance is in the eye of the beholder; the following (replacing the duplicated code here part) is certainly less redundant:

for i in xrange(2):
    if headA is not None:
        if ( headB and headA.data&lt;=headB.data) or (headB is None):
            tail.next = headA
            tail = headA
            headA = headA.next
    # When i==0, this will flip headA &amp; headB
    # When i==1, it will restore them
    headA,headB = headB,headA