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

I. Consider the definition of LinkedBag\'s add method that appears in Segment 3.

ID: 3907496 • Letter: I

Question

I. Consider the definition of LinkedBag's add method that appears in Segment 3.12 in the book. Interchange the second and third statements in the method's body, as follows: firstNode newNode newNode.next firstNode; a. What is displayed by the following statements in a client of the modified LinkedBag? Baginterface myBag = new LinkedBag?(); nyBag. add ("30myBag.add("40")7 myBag.add50") myBag. add ("10") myBag.add("60") myBag.add(20") int numberofEntries myBag.getCurrentsize object[] entries nyBag.toArray for int index 0: index

Explanation / Answer

Hello,

I have gone throught the book "Datastructures and abstractions with Java" and segment 3.12 in it.

Seen all method definitions. And writing the answer accordingly from below:

###################################################################

[1] =>

#################Given add() definition:######################

public boolean add(T newEntry)

{ // add to beginning of chain:

Node newNode = new Node(newEntry);

newNode.next = firstNode;

firstNode = newNode;

numberOfEntries++;

return true;

} // end add

################Modified add as instructed above################################

public boolean add(T newEntry)

{ // add to beginning of chain:

Node newNode = new Node(newEntry);

firstNode = newNode;

newNode.next = firstNode;

numberOfEntries++;

return true;

} // end add

############################################################

So following above new code:

Answer of a):->20 20 20 20 20 20

Answer of b):->Due to change in add, adding new element is failing. New modified code doesnt maintain the linking of

nodes properly. So the method toArray() is failing to return whole linkedBags node's array. Instead it

is returning array containing first element noOfEntries times.

########################################################################

[2]=>

The code I have provided as per asked will not affect any other method in LinkedBag class. Because I have handled all the cases carefully in code. You will have to import java.util.Random.

public T remove()
{
T result = null;
Random rand = new Random();
int r = rand.next(this.numberOfEntries)
int i=0;
Node temp=firstNode;
Node prev=null;

if(r==0) {

if(firstNode != null)
{
result = firstNode.data;
firstNode = firstNode.next;
numberOfEntries--
}

else {
    while(i<r && firstNode!=null) {    
        i++;
        prev=firstNode;
        firstNode=firstNode.next;
    }

    result = firstNode.data;
    prev.next=firstNode.next;
    firstNode=temp;
    numberOfEntries--;
}

return result;
}

############################################################################

Dont hesitate to ask queries and modifications in the code.

Thank You!!!!!