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

Data Structure in Java Task 1: You will modify the add method in the LinkedBag c

ID: 3883506 • Letter: D

Question

Data Structure in Java

Task 1:

You will modify the add method in the LinkedBag class.
Add a second parameter to the method header that will be a boolean variable:

public boolean add(T newEntry, boolean sorted)

The modification to the add method will make it possible to add new entries to the beginning of the list, as it does now, but also to add new entries in sorted order. The sorted parameter if set to false will result in the existing functionality being executed (it will add the new element to the beginning of the list), if set to true the new element will be inserted into the list such that the list is in sorted order.

So for example if these are the current entries in the list: 5 -> 8 -> 10 -> 16 -> 25

And the new entry that I want to put into the list is 14, it will put it into the list between 10 and 16: 5 -> 8 -> 10 -> 14 -> 16 -> 25

Remember, this is a generic class so it needs to be able to process any kind of object, just as it does now.

Task 2:

You will need to modify the add method header in the BagInterface class also to include the new parameter.

Task 3:

Create a test program to thoroughly test the add method. Name this file LinkedBagTester.java.

Part of this assignment is to create test cases that test all possible conditions of adding data into the list to verify that the new entry will get placed into the correct place in the list. Also, you need to test the conditions of adding elements only to the beginning of the list so that you verify that your changes did not break the existing functionality.

Explanation / Answer

As code is not shared here is my code for this

Add this in LinkedBag.java and change header to

public final class LinkedBag<T extends Comparable <T>> implements BagInterface<T>

public boolean add(T newEntry, boolean sorted)
{
if (!sorted || newEntry.compareTo(firstNode.data) < 0) {
return add(newEntry);
}
Node temp = firstNode;
Node prev = null;;
Node newNode = new Node(newEntry);
Boolean inserted = false;
while(temp.next != null)
{
prev = temp;
temp = temp.next;
if (newEntry.compareTo(temp.data) < 0) {
newNode.next = temp;
prev.next = newNode;
inserted = true;
}
}
if (!inserted)
{
prev.next = newNode;
}
return true;
}

In BagInterface

add

public boolean add(T newEntry, boolean sorted);