Merge two sorted lists ( in | Python3 program to merge two sorted linked lists in - place . ; Function to create newNode in a linkedlist ; A utility function to print linked list ; Merges two given lists in - place . This function mainly compares head nodes and calls mergeUtil ( ) ; start with the linked list whose head data is the least ; Driver Code ; 1.3 . 5 LinkedList created ; 0.2 . 4 LinkedList created
import math NEW_LINE 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 newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def printList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT def merge ( h1 , h2 ) : NEW_LINE INDENT if ( h1 == None ) : NEW_LINE INDENT return h2 NEW_LINE DEDENT if ( h2 == None ) : NEW_LINE INDENT return h1 NEW_LINE DEDENT if ( h1 . data < h2 . data ) : NEW_LINE INDENT h1 . next = merge ( h1 . next , h2 ) NEW_LINE return h1 NEW_LINE DEDENT else : NEW_LINE INDENT h2 . next = merge ( h1 , h2 . next ) NEW_LINE return h2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = newNode ( 1 ) NEW_LINE head1 . next = newNode ( 3 ) NEW_LINE head1 . next . next = newNode ( 5 ) NEW_LINE head2 = newNode ( 0 ) NEW_LINE head2 . next = newNode ( 2 ) NEW_LINE head2 . next . next = newNode ( 4 ) NEW_LINE mergedhead = merge ( head1 , head2 ) NEW_LINE printList ( mergedhead ) NEW_LINE DEDENT