Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// Java code: class IntListElement { IntListElement(int value, IntListElement e)

ID: 3820851 • Letter: #

Question

// Java code:

class IntListElement {  

IntListElement(int value, IntListElement e) {    

data = value;    

next = e;  

}  

IntListElement next;  

int data;

}

class Main1 {  

public static void main(String[] args) {     

IntListElement e1 = new IntListElement(1776,null);     

e1 = new IntListElement(1984, e1);     

e1 = new IntListElement(2001, e1);     

e1 = new IntListElement(2013, e1);     

System.out.println(e1.data);           // prints _______     

System.out.println(e1.next.next.data); // prints _______  

}

}

(a) Write a method findLargest that takes a reference to an IntListElement, list, and returns the value of the largest integer stored in the list. E.g. If the list myList contained 3, 4, 5, 1 then x = findLargest(myList) would assign x to be 5. You should assume that the list is not empty.

(b) Write a method get(), to be added to the IntListElement class that takes one integer parameters, n, and returns the value stored in the data field of the nth element of the list (starting with 0 being the first element). For example if myList pointed to the list containing the 5 elements 100, 200, 300, 400, 500 then executing x = myList.get(3); would store 400 in x.

Explanation / Answer

1. To find the largest number in the list
I have added an extra feature which was nott required i.e. smallest number.

public class Array
{
public static void main(String[] args)
{
int arr[]={1,120,56,78,87};
int largest=arr[0];
int smallest=arr[0];
int small=0;
int index=0;
for(int i=1;i<arr.length;i++)
{
if(arr[i]>largest)
{
largest=arr[i];
index=i;
}
else if(smallest>arr[i])
{
smallest=arr[i];
small=i;
}
}
System.out.println(largest);
System.out.println(index);
System.out.println(smallest);
System.out.println(small);
}
}

2. To retrieve the last number in the array.


import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
   // retrieves element at 4th postion
int retval=arrlist.get(3);
System.out.println("Retrieved element is = " + retval);     
}
}

Hope it helps..!!