text: Rearrange a given linked list in | Python3 code to rearrange linked list in place ; Function for rearranging a linked list with high and low value ; Base case ; Two pointer variable ; Swap function for swapping data ; Swap function for swapping data ; Function to insert a node in the linked list at the beginning ; Function to display node of linked list ; Driver code ; Let create a linked list 9 . 6 . 8 . 3 . 7
code: class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def rearrange ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT prev , curr = head , head . next NEW_LINE while ( curr ) : NEW_LINE INDENT if ( prev . data > curr . data ) : NEW_LINE INDENT prev . data , curr . data = curr . data , prev . data NEW_LINE DEDENT if ( curr . next and curr . next . data > curr . data ) : NEW_LINE INDENT curr . next . data , curr . data = curr . data , curr . next . data NEW_LINE DEDENT prev = curr . next NEW_LINE if ( not curr . next ) : NEW_LINE INDENT break NEW_LINE DEDENT curr = curr . next . next NEW_LINE DEDENT return head NEW_LINE DEDENT def push ( head , k ) : NEW_LINE INDENT tem = Node ( k ) NEW_LINE tem . data = k NEW_LINE tem . next = head NEW_LINE head = tem NEW_LINE return head NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT curr = head NEW_LINE while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE curr = curr . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 9 ) NEW_LINE head = rearrange ( head ) NEW_LINE display ( head ) NEW_LINE DEDENT