Please write following program in JAVA. Thanks! Create a class named MyList. It
ID: 3911997 • Letter: P
Question
Please write following program in JAVA. Thanks!
Create a class named MyList. It will use a "Linked List" of integers as its attribute. The constructor will simply create an empty list. This will be a different type of Linked List, as all of the items will be in ascending numerical order. That means items wil not necessarily be placed at the end of the list, but where it should be located. Your list should only contain unique items. Therefore, if your add0 method is passed an integer that already exists on the list, do not add it. The list should contain only one instance of an integer; no duplicate values. Note that the iterator simply uses the next0 method, so if you use the iterator to find the location, you may need to keep track of the current index yourself. The following are the methods to create for this class: 1. add(value) : Add the specified integer value to its appropriate place on the list 2. remove(value) : Remove the specified value from the list 3. list0 This method uses the iterator to print the contents of the list. It should appear on the same line, separated by commas. For example: 1,3, 4, 6, 8 Note that the last item will NOT have a comma following it. 4. maxgap0: This method will return the largest difference between items on the list. For example, in the sample list displayed in #3 above, the largest gap is 2 (between 4 and 6 and between 6 and 8)Explanation / Answer
Java:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
MyList lst=new MyList();
lst.add(10);
lst.add(4);
lst.add(25);
lst.add(8);
lst.add(1);
lst.add(18);
lst.remove(18);
System.out.println(lst.maxgap());
}
}
class MyList
{
private LinkedList<Integer> list;
public MyList(){
list=new LinkedList<Integer>();
}
public void add(int n){
if(!list.contains(n)){
if(list.isEmpty()||n<list.get(0)){
list.addFirst(n);
}else if(n>list.get(list.size()-1)){
list.addLast(n);
}else{
for(int i=0;i<list.size()-1;i++){
if(n>list.get(i)&&n<list.get(i+1)){
list.add(i+1,n);
return;
}
}
}
}
}
public void remove(int n){
list.remove(new Integer(n));
}
public void list(){
Iterator it=list.iterator();
if(it.hasNext())
System.out.print(it.next());
while(it.hasNext()){
System.out.print(","+it.next());
}
}
public int maxgap(){
int largestGap=1;
for(int i=0;i<list.size()-1;i++){
int gap=list.get(i+1)-list.get(i);
if(largestGap<gap){
largestGap=gap;
}
}
return largestGap;
}
}