Question
Produce a method that gets the last index of a given integer and returns it. Call this method: LastIndexOf a. Parameter(s): a LinkedList, an Integer
Produce a method that gets the last index of a given integer and returns it. Call this method: LastIndexOf
a. Parameter(s): a LinkedList, an Integer b. Returns: an Integer c. Ex. Input (as LinkedList elements): [1,6,8,4,6,7], 6. Output: 4. There are 2
indexes where 6 is available 1 and 4. The method returns the last one.
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, 1); list = LUCLinkedList.insert(list, 6); list = LUCLinkedList.insert(list, 8); list = LUCLinkedList.insert(list, 4); list = LUCLinkedList.insert(list, 6); System.out.println(LUCLinkedList.printList(list)); // System.out.println(LUCLinkedList.LastIndexOf(list, 6)); */ } }
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 code here
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Here is the solution for above problem i did this code in java programming language import javaio cl...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started