Make middle node head in a linked list | Linked List node ; function to get the middle node set it as the beginning of the linked list ; to traverse nodes one by one ; to traverse nodes by skipping one ; to keep track of previous middle ; for previous node of middle node ; move one node each time ; move two nodes each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate new node ; link the old list to new node ; move the head to point the new node ; A function to print a given linked list ; Create a list of 5 nodes
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 setMiddleHead ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT one_node = head NEW_LINE two_node = head NEW_LINE prev = None NEW_LINE while ( two_node != None and two_node . next != None ) : NEW_LINE INDENT prev = one_node NEW_LINE one_node = one_node . next NEW_LINE two_node = two_node . next . next NEW_LINE DEDENT prev . next = prev . next . next NEW_LINE one_node . next = head NEW_LINE head = one_node NEW_LINE return head NEW_LINE DEDENT def push ( head , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head NEW_LINE head = new_node NEW_LINE return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( str ( temp . data ) , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT head = None NEW_LINE for i in range ( 5 , 0 , - 1 ) : NEW_LINE INDENT head = push ( head , i ) NEW_LINE DEDENT print ( " ▁ list ▁ before : ▁ " , end = " " ) NEW_LINE printList ( head ) NEW_LINE head = setMiddleHead ( head ) NEW_LINE print ( " ▁ list ▁ After : ▁ " , end = " " ) NEW_LINE printList ( head ) NEW_LINE