Hi! I have a method that inserts a node but does not check whether the item to b
ID: 3632599 • Letter: H
Question
Hi! I have a method that inserts a node but does not check whether the item to be inserted is already in the list. I need it modified to check for duplicates. Thanks!public void insertNode(DataElement insertItem)
{
LinkedListNode current; //variable to traverse the list
LinkedListNode trailCurrent; //variable just before current
LinkedListNode newNode; //variable to create a node
boolean found;
newNode = new LinkedListNode(); //create the node
newNode.info = insertItem.getCopy(); //store newItem in the node
newNode.link = null; //set the link field of the node to null
if(first == null) //Case 1
{
first = newNode;
count++;
}
else
{
trailCurrent = first;
current = first;
found = false;
while(current != null && !found) //search the list
if(current.info.compareTo(insertItem) >= 0)
found = true;
else
{
trailCurrent = current;
}
if(current == first) //Case 2
{
newNode.link = first;
first = newNode;
count++;
}
else //Case 3
{
trailCurrent.link = newNode;
newNode.link = current;
count++;
}
}
}
Explanation / Answer
public void insertNode(DataElement insertItem)
{
LinkedListNode current; //variable to traverse the list
LinkedListNode trailCurrent; //variable just before current
LinkedListNode newNode; //variable to create a node
boolean found;
newNode = new LinkedListNode(); //create the node
newNode.info = insertItem.getCopy(); //store newItem in the node
newNode.link = null; //set the link field of the node to null
if(first == null) //Case 1
{
first = newNode;
count++;
}
else
{
trailCurrent = first;
current = first;
found = false;
while(current != null && !found) //search the list
if(current.info.compareTo(insertItem) >= 0)
found = true;
else
{
trailCurrent = current;
}
if(found)
{
system.out.println("Item already exist, do u want to insert anyway..(Y/N)");
char myChar = (char) System.Console.Read();
if (mychar=='n' ||mychar=='N')
exit(0);
}
if(current == first) //Case 2
{
newNode.link = first;
first = newNode;
count++;
}
else //Case 3
{
trailCurrent.link = newNode;
newNode.link = current;
count++;
}
}
}
Note:
In the lines written in RED, i have checked whether the item is found or not.
If found i will aks the user that it already exist ,do u want to add anyway.
If he will enter yes then i will continue
if he will enter NO i will exit from the function.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.