Question

In: Computer Science

3. Find the last node of a linked list of n elements whose index is a...

3. Find the last node of a linked list of n elements whose index is a multiple of k (counted from 0). For example, if the list is

12 → 75 → 37 → 99 → 12 → 38 → 99 → 60 ↓

and k = 4, then it should return the second 12 (with index 4). The algorithm should take O(n) time and use O(1) extra space. Implement the following method in LinkedList.java. public T lastK(int k)

Solutions

Expert Solution

The method used to find the last element whose index value is divisible by given number is as follows.

If the list is empty, print that list is empty and stop. Otherwise take the first node of the list and store its value in a variable 'element'. Now traverse the list using while loop. If the index value of the current node is divisible by k then update the value of 'element' with the current node value. Repeat this step until the list is travered.


// import io library to take input from the user
import java.io.*; 
  
// Java program to implement a linked list
public class LinkedList { 

    Node head; // head of list 
        // create linked list object
        public static LinkedList list = new LinkedList();
    
        // Linked list Node. 
    // This inner class is made static 
    // so that main() can access it 
    static class Node { 

    // create variable and object data and nextdata node for pointing to nextdata node  
        int data; 
        Node nextdata; 
  
        // create Constructor 
        Node(int d) 
        { 
            data = d; 
            nextdata = null; 
        } 
    } 
  
    // Method to add a new node 
    public static LinkedList add(LinkedList list, int data) 
    { 
        // Create a new node with given data 
        Node newdata = new Node(data); 
        newdata.nextdata = null; 
  
        // If the Linked List is empty, 
        // then make the new node as head 
        if (list.head == null) { 
            list.head = newdata; 
        } 
        else { 
            // id list is non empty then traverse the list
            // and add the newdata at the end
            Node last = list.head; 
            while (last.nextdata != null) { 
                last = last.nextdata; 
            } 
  
            // add the newdata at end 
            last.nextdata = newdata; 
        } 
  
        // Return the list 
        return list; 
    } 
  
    // Method to print the LinkedList. 
    public static void printnodes() 
    { 
        Node currentNode = list.head; 
        System.out.print("LinkedList: "); 
   
        // Traverse the LinkedList 
        while (currentNode != null) { 
            // Print the data at current node 
            System.out.print(currentNode.data + " "); 
   
            // Go to nextdata node 
            currentNode = currentNode.nextdata; 
        } 
    } 
        
        // Method to find the last element 
        // whose index is multiple of given number
        public static void lastK(int k)
        {
                int index = 0;    // take first index as 0
                Node currentNode = list.head;
                int element = 0;        
                
                // check if the list is empty
                if(currentNode == null)
                {
                        System.out.println("\nList is empty");
                }
                else
                {
                        // if the list is not empty, take first value of list as element
                        element = currentNode.data;
                        
                        // traverse the list 
                        while (currentNode != null) { 
                                // Print the data at current node 
                                // if the index value is divisible by k,
                                // update the value of element with the current node value
                                if(index%k==0)
                                        element = currentNode.data;
                                
                                // increment the index value
                                index++;
   
                                // Go to nextdata node 
                                currentNode = currentNode.nextdata; 
                        }
                        
                        // print the answer
                        System.out.println("\nLast element whose index is multiple of "+k+" = "+element);
        } 
                
        }
        
        // main method
    public static void main(String[] args) throws IOException
    {           
        
                // create BufferedReader to take input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                
                // input number of nodes in the linked list
                System.out.println("Enter number of nodes in linked list:");
                int n = Integer.parseInt(br.readLine());
                
                // input nodes using for loop
                System.out.println("Enter nodes:");
                for(int i=0;i<n;i++){
                        int x = Integer.parseInt(br.readLine());
                        
                        // add node in linked list
                        list = add(list,x);
                }
                
                // input value of k
                System.out.println("Enter value of k:");
                int k = Integer.parseInt(br.readLine());
  
        
        // Print the LinkedList 
        printnodes();
                // find the node whose index is multiple of given number
                lastK(k);
    } 
} 

In finding the last element with index multiple of k, we are scanning the list from starting to end one time, so the time complexity of the algorithm is O(n), where n is the number of nodes present in linked list.

Space complexity will be O(1) because we are using only one variable to store the result.

Function screenshot

Output screenshot:


Related Solutions

Find the last node of a linked list of n elements whose index is a multiple...
Find the last node of a linked list of n elements whose index is a multiple of k (counted from 0). For example, if the list is 12 → 75 → 37 → 99 → 12 → 38 → 99 → 60 ↓ and k = 4, then you should return the second 12 (with index 4). Your algorithm should take O(n) time and use O(1) extra space. Implement the following method in LinkedList.java. public T lastK(int k) LinkedList.java. public...
Python 3 Function which takes the head Node of a linked list and sorts the list...
Python 3 Function which takes the head Node of a linked list and sorts the list into non-descending order. PARAM: head_node The head of the linked list RETURNS: The node at the head of the sorted linked list. ''' def sort(head_node): #Code goes here ''' Test code goes here '' ' if __name__ == '__main__':
Assume that a singly linked list is implemented with a header node, but no tail node,...
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a pointer to the header node. Write a class in C++ that includes methods to a. return the size of the linked list b. print the linked list c. test if a value x is contained in the linked list d. add a value x if it is not already contained in the linked list e. remove a value...
Assume that a singly linked list is implemented with a header node, but no tail node,...
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a pointer to the header node. Write a class that includes methods to a. return the size of the linked list b. print the linked list c. test if a value x is contained in the linked list d. add a value x if it is not already contained in the linked list e. remove a value x if...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment? x.next = x.next.next b. Singly Linked List has two private instance variables first and last as that point to the first and the last nodes in the list, respectively. Write a fragment of code that removes the last node in a linked list whose first node is first....
I've provided a Node class that implements a node of a simple singly-linked list (with .value...
I've provided a Node class that implements a node of a simple singly-linked list (with .value and .next fields), and an empty LinkedList class. Your task is to implement LinkedList.sort(l), where given the node l as the head of a singly-linked list, LinkedList.sort(l) sorts the nodes in the list into ascending order according to the values in the .value field of each node. Your implementation should do an in-place update of the list. It is ok to use a simple...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
Complete the following program:LinkedQueue.zip package jsjf; /** * Represents a node in a linked list. */...
Complete the following program:LinkedQueue.zip package jsjf; /** * Represents a node in a linked list. */ public class LinearNode<T> {    private LinearNode<T> next;    private T element;    /**    * Creates an empty node.    */    public LinearNode()    {        next = null;        element = null;    }    /**    * Creates a node storing the specified element.    * @param elem element to be stored    */    public LinearNode(T elem)...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
You are given a reference to the head node of a linked list that stores integers....
You are given a reference to the head node of a linked list that stores integers. Please print the minimum element in this linked list. The class ListNode.java contains the description of a single node in the linked list. It has a num field to store the integer number and a reference next that points to the next element in the list. The file MyList.class is a pre-defined java code, that creates a linked list. The file ListSmallest.java creates an...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT