Alternate Odd and Even Nodes in a Singly Linked List | Link list node ; A utility function to print linked list ; Function to create newNode in a linkedlist ; Function to insert at beginning ; Function to rearrange the odd and even nodes ; Odd Value in Even Position Add pointer to current node in odd stack ; Even Value in Odd Position Add pointer to current node in even stack ; Swap Data at the top of two stacks ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT 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 print ( " " ) NEW_LINE DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def insertBeg ( head , val ) : NEW_LINE INDENT temp = newNode ( val ) NEW_LINE temp . next = head NEW_LINE head = temp NEW_LINE return head NEW_LINE DEDENT def rearrangeOddEven ( head ) : NEW_LINE INDENT odd = [ ] NEW_LINE even = [ ] NEW_LINE i = 1 NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( head . data % 2 != 0 and i % 2 == 0 ) : NEW_LINE INDENT odd . append ( head ) NEW_LINE DEDENT elif ( head . data % 2 == 0 and i % 2 != 0 ) : NEW_LINE INDENT even . append ( head ) NEW_LINE DEDENT head = head . next NEW_LINE i = i + 1 NEW_LINE DEDENT while ( len ( odd ) != 0 and len ( even ) != 0 ) : NEW_LINE INDENT odd [ - 1 ] . data , even [ - 1 ] . data = even [ - 1 ] . data , odd [ - 1 ] . data NEW_LINE odd . pop ( ) NEW_LINE even . pop ( ) NEW_LINE DEDENT return head NEW_LINE DEDENT head = newNode ( 8 ) NEW_LINE head = insertBeg ( head , 7 ) NEW_LINE head = insertBeg ( head , 6 ) NEW_LINE head = insertBeg ( head , 5 ) NEW_LINE head = insertBeg ( head , 3 ) NEW_LINE head = insertBeg ( head , 2 ) NEW_LINE head = insertBeg ( head , 1 ) NEW_LINE print ( " Linked ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE rearrangeOddEven ( head ) NEW_LINE print ( " Linked ▁ List ▁ after ▁ " , " Rearranging : " ) NEW_LINE printList ( head ) NEW_LINE