Delete middle of linked list | Link list Node ; Count of nodes ; Deletes middle node and returns head of the modified list ; Base cases ; Find the count of nodes ; Find the middle node ; Delete the middle node ; Delete the middle node ; A utility function to print a given linked list ; Utility function to create a new node . ; Driver Code ; Start with the empty list
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def countOfNodes ( head ) : NEW_LINE INDENT count = 0 NEW_LINE while ( head != None ) : NEW_LINE INDENT head = head . next NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def deleteMid ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( head . next == None ) : NEW_LINE INDENT del head NEW_LINE return None NEW_LINE DEDENT copyHead = head NEW_LINE count = countOfNodes ( head ) NEW_LINE mid = count // 2 NEW_LINE while ( mid > 1 ) : NEW_LINE INDENT mid -= 1 NEW_LINE head = head . next NEW_LINE DEDENT head . next = head . next . next NEW_LINE return copyHead NEW_LINE DEDENT def printList ( ptr ) : NEW_LINE INDENT while ( ptr != None ) : NEW_LINE INDENT print ( ptr . data , end = ' - > ' ) NEW_LINE ptr = ptr . next NEW_LINE DEDENT print ( ' NULL ' ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . data = data NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE print ( " Gven ▁ Linked ▁ List " ) NEW_LINE printList ( head ) NEW_LINE head = deleteMid ( head ) NEW_LINE print ( " Linked ▁ List ▁ after ▁ deletion ▁ of ▁ middle " ) NEW_LINE printList ( head ) NEW_LINE DEDENT