Remove every k | Linked list Node ; To remove complete list ( Needed for case 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 ; set count = 0 to reach further k - th Node ; update prev if count is not 0 ; Function to prvar linked list ; Utility function to create a new node . ; Start with the empty list
class Node { constructor ( ) { this . data = 0 ; this . next = null ; } } function freeList ( node ) { while ( node != null ) { next = node . next ; node = next ; } return node ; } function deleteKthNode ( head , k ) { if ( head == null ) return null ; if ( k == 1 ) { head = freeList ( head ) ; return null ; } var ptr = head , prev = null ; var count = 0 ; while ( ptr != null ) { count ++ ; if ( k == count ) { prev . next = ptr . next ; count = 0 ; } if ( count != 0 ) prev = ptr ; ptr = prev . next ; } return head ; } function displayList ( head ) { temp = head ; while ( temp != null ) { document . write ( temp . data + " " ) ; temp = temp . next ; } } function newNode ( x ) { temp = new Node ( ) ; temp . data = x ; temp . next = null ; return temp ; } head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 5 ) ; head . next . next . next . next . next = newNode ( 6 ) ; head . next . next . next . next . next . next = newNode ( 7 ) ; head . next . next . next . next . next . next . next = newNode ( 8 ) ; var k = 3 ; head = deleteKthNode ( head , k ) ; displayList ( head ) ;