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

Hi need help with this method, as it needs to sort in alphabetical order. public

ID: 3701965 • Letter: H

Question

Hi need help with this method, as it needs to sort in alphabetical order.

public void addElement(Object element)

The addElement adds the parameter element into the linked list. The linked list should contain 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.

It needs to be integrated with an interface. ListIterator.java .

// ListIterator.java

Thanks in advnace

Explanation / Answer

Hi friend, since you have not posted LinkedList class, I can not test.

But based on given information, i have implemented required method.

Please let me know in case of any issue.

public void addElement(Object element)

   {   

          //create newNode

          Node newNode=new Node();

          //Assign element to newNode.data

          newNode.data=element;

          //check first is null

          if(first==null)

          {

              //set newNode.next to NULL

              newNode.next=null;

              //set newNode as first

              first=newNode;

              //exit

              return;

          }

          //if element is alphabetically small then

else if(element.toString(). compareTo(first.data.toString() ) <0)

          {

              //add newNode as the first node

              newNode.next=first;

              first=newNode;

          }

          //if newNode is greater than first.data

          else

          {

              Node pp=first.next;        

              Node prev=first;

              //Loop to find the position for newNode

              while(pp!=null )

              {

                   //if place found then exit

if((element.toString().compareTo ( pp.data.toString())<0))

                        break;

                   //else store current position

                   prev=pp;

                   //move to next position

                  pp=pp.next;

               

              }

             //place newNode

             newNode.next=prev.next;

              prev.next=newNode

          }    

   }

Please DONT forgot to rate my answer. We are working hard for you guys!!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote