char ith datal tox (int3 Write your solution to this question on page 7. As best
ID: 3593624 • Letter: C
Question
char ith datal tox (int3 Write your solution to this question on page 7. As best you can, for partial credit, show all work 27. (10 points) The SortedDoubly LinkedList linked list data stracture is a doubly linked list with the added property that the values in the list are kept in sorted order. The value at the front of the list (position 0) is currently the smallest value in the list and the value at the end of the list (position size0-1) is currenaity the largest value in the list ive Write the implementation of a new method called Sorted Add for the SortedDoublyLinkedList class public void Sortedadd (AnyType newvalue) The method Sorted Add adds the newValue into the list in its appropriate sorted position within the sortesdl doubly linked list. Below is the part of the Sorted DoublytLinkedL ist class which you use for this question. You can' t use any other methods of the SortedDoublyLinkedList class. lic class SortedDoublylinkedList cAnytypes implements List private AnyType data; private NodecAnyType> prev private Node p, Node cAnyType» n) setData(d) setPrev (p) setNext (n): public AnyType getData) return data: public void setData (AnyType d) (data d: ) public Node getPrev() return prev public void setPrev (Node cAnyType> p) prev-p: public NodecAnyType> getNext) return next: public void setNext (NodecAnyType> n) next ) private int modCount private Node header private NodecAnyType> trailer Write your solution to this question on page 8. As best you can, for partial credit, shew all workExplanation / Answer
SortedAdd function :
public void SortedAdd(AnyType data) {
Node nodeToAdd = new Node(data, null, null);
//if list is empty , set node as header,trailer and return
if (header == null) {
header = nodeToAdd;
trailer = nodeToAdd;
return;
}
//if data to add is greater than or equal to trailer , add it after trailer and return
if (data >= trailer.getData()) {
nodeToAdd.setPrev(trailer);
trailer.setNext(nodeToAdd);
trailer = nodeToAdd;
return;
}
//if data to add is less than or equal header , add it before header and return
if (data <= header.getData()) {
nodeToAdd.setNext(header);
header.setPrev(nodeToAdd);
header = nodeToAdd;
return
}
//iterate over the list and add new node when position found
Node temp = header.getNext();
while (temp.getNext() != null) {
if (data < temp.getData()) {
Node prev = temp.getPrev();
prev.setNext(nodeToAdd);
nodeToAdd.setPrev(prev);
nodeToAdd.setNext(temp);
temp.setPrev(nodeToAdd);
return;
}
temp = temp.getNext();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.