java help 12. (15 points) Suppose we had a new type of LinkedList, called the So
ID: 3755356 • Letter: J
Question
java help
12. (15 points) Suppose we had a new type of LinkedList, called the SortedLinkedList, which is a linked list, but it keeps all the items in the list sorted. As a result, when we add an item to a SortedLinkedList, we don't provide an index, as the SortedLinkedList figures out where to put the new item based on the values already in the list Your task is is to complete the add method for a SortedLinkedList, shown below. This method inserts a new item into the SortedLinkedList in such a way that the list remains sorted. For example, if the list is 1,2,5 aud we call add (4), tlhe becoues 1.2,4.5] For simplicity: . You can use either a singly or doubly linked list. you can use , andto compare items, but if yotu remember how to use compareTo(), you can do so for extra credit . You may not call the add(int index, E item) method. You may not call the getNode() method (although you may rewrite it) public void add(E item)(Explanation / Answer
I am taking SortedLinkedList as a doubly linked list here.
Defined as :
class SortedLinkedList{
E item;
SortedLinkedList prev; //Reference to previous node of linkedlist.
SortedLinkedList next; //Reference to next node of a linked list.
}
Here first we must have a reference to head node of SortedLinkedList.
So, let it be defined as :
SortedLinkedList head;
void add( E item)
{
SortedLinkedList temp=head;
if(temp==NULL)
{
temp.data=item;
temp.next=NULL;
temp.prev=NULL;
}
else
{
while(temp!=NULL)
{
if(temp.data.compareTo(item)<0)
{
if(temp.next==NULL)
{
SortedLinkedList temp1=new SortedLinkedList();
temp1.data=item;
temp1.prev=temp;
; temp1.next=temp.next;
temp.next=temp1;
break;
}
temp=temp.next;
}
else if(temp.data.compareTo(item)==0)
{
SortedLinkedList temp1=new SortedLinkedList();
temp1.data=item;
temp1.prev=temp;
emp.next=temp.next;
temp.next=temp1;
break;
}
else if(temp.data.compareTo(item)>0)
{
SortedLinkedList temp1=new SortedLinkedList();
temp1.data=item;
temp1.prev=temp.prev;
temp.prev.next=temp1;
temp.prev=temp1;
temp1.next=temp;
temp=temp.next;
break;
}
} //Closing of while loop
} //Closing of else
} //Closing of method add
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.