Remove every k | Python3 program to delete every k - th Node of a singly linked list . ; Linked list Node ; To remove complete list ( Needed forcase when k is 1 ) ; Deletes every k - th node and returns head of modified list . ; If linked list is empty ; Initialize ptr and prev before starting traversal . ; Traverse list and delete every k - th node ; increment Node count ; check if count is equal to k if yes , then delete current Node ; put the next of current Node in the next of previous Node delete ( prev . next ) ; set count = 0 to reach further k - th Node ; update prev if count is not 0 ; Function to print linked list ; Utility function to create a new node . ; Driver Code ; Start with the empty list
import math NEW_LINE 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 freeList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT next = node . next NEW_LINE node = next NEW_LINE DEDENT return node NEW_LINE DEDENT def deleteKthNode ( head , k ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT freeList ( head ) NEW_LINE return None NEW_LINE DEDENT ptr = head NEW_LINE prev = None NEW_LINE count = 0 NEW_LINE while ( ptr != None ) : NEW_LINE INDENT count = count + 1 NEW_LINE if ( k == count ) : NEW_LINE INDENT prev . next = ptr . next NEW_LINE count = 0 NEW_LINE DEDENT if ( count != 0 ) : NEW_LINE INDENT prev = ptr NEW_LINE DEDENT ptr = prev . next NEW_LINE DEDENT return head NEW_LINE DEDENT def displayList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = ' ▁ ' ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT def newNode ( x ) : NEW_LINE INDENT temp = Node ( x ) NEW_LINE temp . data = x 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 head . next . next . next . next = newNode ( 5 ) NEW_LINE head . next . next . next . next . next = newNode ( 6 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 7 ) NEW_LINE head . next . next . next . next . next . next . next = newNode ( 8 ) NEW_LINE k = 3 NEW_LINE head = deleteKthNode ( head , k ) NEW_LINE displayList ( head ) NEW_LINE DEDENT