Create new linked list from two given linked list with greater element at each node | Node class ; Function to insert node in a linked list ; Function which returns new linked list ; Compare for greater node ; Driver Code ; First linked list ; Second linked list
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def insert ( root , item ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = item NEW_LINE temp . next = None NEW_LINE if ( root == None ) : NEW_LINE INDENT root = temp NEW_LINE DEDENT else : NEW_LINE INDENT ptr = root NEW_LINE while ( ptr . next != None ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE DEDENT ptr . next = temp NEW_LINE DEDENT return root NEW_LINE DEDENT def newList ( root1 , root2 ) : NEW_LINE INDENT ptr1 = root1 NEW_LINE ptr2 = root2 NEW_LINE root = None NEW_LINE while ( ptr1 != None ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . next = None NEW_LINE if ( ptr1 . data < ptr2 . data ) : NEW_LINE INDENT temp . data = ptr2 . data NEW_LINE DEDENT else : NEW_LINE INDENT temp . data = ptr1 . data NEW_LINE DEDENT if ( root == None ) : NEW_LINE INDENT root = temp NEW_LINE DEDENT else : NEW_LINE INDENT ptr = root NEW_LINE while ( ptr . next != None ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE DEDENT ptr . next = temp NEW_LINE DEDENT ptr1 = ptr1 . next NEW_LINE ptr2 = ptr2 . next NEW_LINE DEDENT return root NEW_LINE DEDENT def display ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print ( root . data , " - > " , end = " ▁ " ) NEW_LINE root = root . next NEW_LINE DEDENT print ( " ▁ " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = None NEW_LINE root2 = None NEW_LINE root = None NEW_LINE root1 = insert ( root1 , 5 ) NEW_LINE root1 = insert ( root1 , 2 ) NEW_LINE root1 = insert ( root1 , 3 ) NEW_LINE root1 = insert ( root1 , 8 ) NEW_LINE print ( " First ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root1 ) NEW_LINE root2 = insert ( root2 , 1 ) NEW_LINE root2 = insert ( root2 , 7 ) NEW_LINE root2 = insert ( root2 , 4 ) NEW_LINE root2 = insert ( root2 , 5 ) NEW_LINE print ( " Second ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root2 ) NEW_LINE root = newList ( root1 , root2 ) NEW_LINE print ( " New ▁ List : ▁ " , end = " ▁ " ) NEW_LINE display ( root ) NEW_LINE DEDENT