Question: Make a method that computes and returns the sum of the elements from their indices (which are provided in another LinkedList). Assume the LinkedList with

Make a method that computes and returns the sum of the elements from their indices (which are provided in another LinkedList). Assume the LinkedList with the indices is already sorted. Call this method: SumFromIndices

a. Parameter(s): a LinkedList, a LinkedList b. Returns: an Integer c. Ex. Input (as LinkedList elements): [10,25,33,48], [0,2]. Output: 43 (the values at

indices 0 and 4 are 10 and 33 respectively, 10 + 33 = 43)

Main method:

class Main { public static void main(String[] args) { System.out.println("Hello world!"); /*Code for testing LUCLinkedList list = new LUCLinkedList(); list = LUCLinkedList.insert(list, 11); list = LUCLinkedList.insert(list, 25); list = LUCLinkedList.insert(list, 9); list = LUCLinkedList.insert(list, 5); LUCLinkedList list2 = new LUCLinkedList(); list2 = LUCLinkedList.insert(list2, 1); list2 = LUCLinkedList.insert(list2, 2); System.out.println(LUCLinkedList.printList(list)); System.out.println(LUCLinkedList.SumFromIndices(list, list2)); */ } }

import java.io.*;

public class LUCLinkedList {// a Singly Linked List Node head; // head of list public static LUCLinkedList insert(LUCLinkedList list, int data) // Method to insert a new node { Node new_node = new Node(data); // Create a new node with given data new_node.next = null; if (list.head == null) { // If the Linked List is empty, then make the new node as head list.head = new_node; } else {// Else traverse till the last node and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } last.next = new_node; // Insert the new_node at last node } return list; }

//updated method to return string instead of void public static String printList(LUCLinkedList list) // Method to print the LinkedList. { String s = "LinkedList: "; Node currNode = list.head; while (currNode != null) { // Traverse through the LinkedList s += currNode.data + " "; //System.out.print(currNode.data + " "); // Print the data at current node currNode = currNode.next; // Go to next node } return s.trim(); }

//Add your code here

}

Step by Step Solution

3.45 Rating (165 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

implement the SumFromIndices method in the LUCLinkedList class you can follow these steps Traverse t... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!