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

i need help with following java method: public void addElement(Object element) T

ID: 651673 • Letter: I

Question

i need help with following java method:

public void addElement(Object element)

The addElement adds the parameter element into the linked list. The linked list should contains all elements (strings) in alphabetical order. Therefore, in this addElement method, a correct location to insert the parameter element needs to be searched and the element needs to be inserted in that location.

public Object getElement(int index)
{
if (index < 0) throw new IndexOutOfBoundsException();
ListIterator li = listIterator();
while (li.hasNext()) {
Object elt = li.next();
if (index == 0) return elt;
index--;
}
throw new IndexOutOfBoundsException();
}
public void addElement( Object element)
{

????

}

Explanation / Answer

import java.util.NoSuchElementException; public class LinkedList { //nested class to represent a node private class Node { public Object data; public Node next; } //only instance variable that points to the first node. private Node first; // Constructs an empty linked list. public LinkedList() { first = null; } // Returns the first element in the linked list. public Object getFirst() { if (first == null) { NoSuchElementException ex = new NoSuchElementException(); throw ex; } else return first.data; } // Removes the first element in the linked list. public Object removeFirst() { if (first == null) { NoSuchElementException ex = new NoSuchElementException(); throw ex; } else { Object element = first.data; first = first.next; //change the reference since it's removed. return element; } } // Adds an element to the front of the linked list. public void addFirst(Object element) { //create a new node Node newNode = new Node(); newNode.data = element; newNode.next = first; //change the first reference to the new node. first = newNode; } // Returns an iterator for iterating through this list. public ListIterator listIterator() { return new LinkedListIterator(); } //toString method public String toString(){ LinkedListIterator iterator = new LinkedListIterator(); String result = "{ "; while(iterator.hasNext()) result += (iterator.next()+" "); result += "}n"; return result; } //isEmpty method public boolean isEmpty(){ LinkedListIterator it = new LinkedListIterator(); if(!it.hasNext()) return true; else return false; } //addElement method public void addElement(int index, Object element){ if(index size()-1) {NoSuchElementException ex = new NoSuchElementException(); throw ex;} Object result = null; LinkedListIterator it = new LinkedListIterator(); result = getElement(index); if(index