This lab is to expose you to a singly Linked List of String. The add( ) method i
ID: 3908166 • Letter: T
Question
This lab is to expose you to a singly Linked List of String.
The add( ) method in the StringLinkedBag.java in Canvas, adds to the end of the Linked List. Modify the add( ) method to maintain a..z order. Make sure your revised add( ) method as O(n) in the worst case scenario. Make sure you add your name to the comments before the add method.
public class StringLinkedBag
{
private StringNode head;
private StringNode tail;
private int numElements;
/**
* No-arg Constructor
*/
public StringLinkedBag( )
{
head = null;
tail = null;
numElements = 0;
}
/**
* The getSize method returns the linked bag's current size.
* @return The value in the numElements field.
*/
public int getSize()
{
return numElements;
}
/**
* The add method adds a String to the linked bag
* This version just sticks the value at the end of the list
* @param newElement The String to be added to the linked bag.
*/
public void add(String newElement)
{
if (tail == null) // is list empty?
{
head = new StringNode(newElement, null);
tail = head;
}
else
{
tail.setLink(new StringNode(newElement,null));
tail = tail.getLink();
}
numElements++;
}
Explanation / Answer
In order to complete the code, I need the StringNode class which is not provided in the question. All I need is the name of the method which returns the data inside the node. I assumed that the StringNode class has a getElement() method. In case the code does not compile, please let me know, I'll surely help. Post a comment. Its just about putting the correct name for the method.
Please do rate the answer if it helped. Thank you.
public class StringLinkedBag
{
private StringNode head;
private StringNode tail;
private int numElements;
/**
* No-arg Constructor
*/
public StringLinkedBag( )
{
head = null;
tail = null;
numElements = 0;
}
/**
* The getSize method returns the linked bag's current size.
* @return The value in the numElements field.
*/
public int getSize()
{
return numElements;
}
/**
* The add method adds a String to the linked bag
* This version will maintain the bag in a..z order
* @param newElement The String to be added to the linked bag.
*/
public void add(String newElement)
{
StringNode n = new StringNode(newElement, null);
if (tail == null) // is list empty?
{
head = n;
tail = head;
}
else
{
StringNode current = head;
StringNode previous = null;
while(current != null)
{
if(newElement.compareToIgnoreCase(current.getData()) < 0)
break;
previous = currrent;
current = current.getLink();
}
n.setLink(current); //make the new node point to current node
if(current == head) //insert as head node, update head
head = n;
else
previous.setLink(n);
if(current == null) //inserted the new node to end of list, update tail
tail = n;
}
numElements++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.