Monday, September 26, 2022

Remove every k'th node

 Problem:

Given a singly linked list, your task is to remove every kth node from the linked list.
Input:
The first line of input contains number of test cases T. Then T test cases follow. Every test case contains 3 lines. First line of every test case contains an integer N denoting the size of the linked list . The second line contains N space separated values of the linked list. The third line contains an integer K.
Output:
Output for each test case will be space separated values of the nodes of the new transformed linked list.
Example:
Input:
2
8
1 2 3 4 5 6 7 8
3
4
1 2 3 4
2
Output:
1 2 4 5 7 8
1 3


My Answer:

  Node delete(Node head, int k)
    {
	// Your code here	 
	    if (head == null || k == 0) return head;
	    if ( k == 1 ) return null;
	    
	    int nth = 1;
	    Node node = head;
	    while (node.next != null) {
	        if ( (nth+1) % k == 0 ) {
	            if ( node.next.next != null) {
	                node.next = node.next.next;
	            } else {
	                node.next = null;
	                break;
	            }
	            
	            nth=nth+1;
	        }
	        nth = nth + 1;
	        node = node.next;
	    }
	    return head;
    }

No comments:

Post a Comment

Search in a matrix

  Problem: Given a matrix  mat [][] of size  N  x  M , where every row and column is sorted in increasing order, and a number  X  is given. ...