text: Rearrange a given linked list in | Python3 implementation ;  ; Function to print the list ; Function to rearrange ; We set left = null , when we reach stop condition , so no processing required after that ; Stop condition : odd case : left = right , even case : left . next = right ; Stop condition , set null to left nodes ; Even case ; Odd case ; Driver code ; Print original list ; Modify the list ; Print modified list
code: class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . next = None NEW_LINE DEDENT DEDENT left = None NEW_LINE def printlist ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " ▁ " ) NEW_LINE if ( head . next != None ) : NEW_LINE INDENT print ( " - > " , end = " " ) NEW_LINE DEDENT head = head . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def rearrange ( head ) : NEW_LINE INDENT global left NEW_LINE if ( head != None ) : NEW_LINE INDENT left = head NEW_LINE reorderListUtil ( left ) NEW_LINE DEDENT DEDENT def reorderListUtil ( right ) : NEW_LINE INDENT global left NEW_LINE if ( right == None ) : NEW_LINE INDENT return NEW_LINE DEDENT reorderListUtil ( right . next ) NEW_LINE if ( left == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( left != right and left . next != right ) : NEW_LINE INDENT temp = left . next NEW_LINE left . next = right NEW_LINE right . next = temp NEW_LINE left = temp NEW_LINE DEDENT else : NEW_LINE INDENT if ( left . next == right ) : NEW_LINE INDENT left . next . next = None NEW_LINE left = None NEW_LINE DEDENT else : NEW_LINE INDENT left . next = None NEW_LINE left = None NEW_LINE DEDENT DEDENT DEDENT head = Node ( 1 ) NEW_LINE head . next = Node ( 2 ) NEW_LINE head . next . next = Node ( 3 ) NEW_LINE head . next . next . next = Node ( 4 ) NEW_LINE head . next . next . next . next = Node ( 5 ) NEW_LINE printlist ( head ) NEW_LINE rearrange ( head ) NEW_LINE printlist ( head ) NEW_LINE