Question: Given a singly linked list and a number K, you are required to complete the function modularNode() which returns the modular node of the linked list. A modular node is the last node of the linked list whose Index is divisible by the number K, i.e. i%k==0. For instance, Linked List: 19->28->37->46->55->6->7->25->2 and k=4. The output should be 25

/**
* Created by aarushi on 29/6/21.
*/
public class P09ModularNode {

public static void main(String[] args){
ListNode node= new ListNode(19);
node= new ListNode(28);
node= new ListNode(37);
node= new ListNode(46);
node= new ListNode(55);
node= new ListNode(6);
node= new ListNode(7);
node= new ListNode(25);
node= new ListNode(2);

//find and print the modular node
if(modularNode(list,4)!=null){
System.out.println(modularNode(list,4).getData());
} else {
System.out.println("Invalid");
}

}

//method to find modular node
public static ListNode modularNode(LinkedList list, int k){

//if value of k is larger than the length of the linked list return null
if(list.findLength()<k){
return null;
}

//temp: pointer which will traverse the linked list

//find the index of the required node
int indexRequired= list.findLength()-(list.findLength()%k);
//index: keeps track of the number of nodes traversed
int index=1;

//reach the indexRequired node
while (temp!=null && index!=indexRequired){
temp=temp.getNext();
index++;
}

//return the node
return temp;
}
}

/**
* Created by aarushi on 24/6/21.
*/
//data fields

}

//if list is empty then set head equal to the node
node.setNext(null);
} else {
//create a pointer- temp
//iterate to the last element
while (temp.getNext() != null) {
temp = temp.getNext();
}
//insert the node at the end of the list
temp.setNext(node);
node.setNext(null);
}
}
}

/**
* This class is the type declaration for a linked list
* Created by aarushi on 24/6/21.
*/
public class ListNode {
//data fields
private int data; //stores the value of the node
private ListNode next; //stores the reference of the next node

//constructor to initialize the value of the node
public ListNode(int data){
this.data= data;
this.subList=null;
}

//accessor method to get the value stored in data
public int getData() {
return this.data;
}

//mutator method to change the value of data
public void setData(int data) {
this.data = data;
}

//accessor method which returns the reference of the next node
public ListNode getNext() {
return this.next;
}

//mutator method which changes the reference of the next node
public void setNext(ListNode next) {
this.next = next;
}

}
Java Programs

This site uses Akismet to reduce spam. Learn how your comment data is processed.